Highlighted

My push message no report

Avatar

Avatar

lawlietl

Avatar

lawlietl

lawlietl

08-08-2018

I can receive message. But My push message no report.

Android

Compile Sdk Version API 26:Android 8.0 (Oreo)

Adobe Library : 4.16.0

Android Code

MyFirebaseMessagingService.java

package com.example.lawlietlin.lawlietdevii;

import android.app.Activity;

import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.media.RingtoneManager;

import android.net.Uri;

import android.os.Build;

import android.support.annotation.RequiresApi;

import android.support.v4.app.NotificationCompat;

import android.util.Log;

import com.adobe.mobile.Config;

import com.google.firebase.messaging.FirebaseMessagingService;

import com.google.firebase.messaging.RemoteMessage;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    Bitmap bitmap;

    @RequiresApi(api = Build.VERSION_CODES.O)

    @Override

    public void onMessageReceived(RemoteMessage remoteMessage) {

        //MyFirebaseMessagingService.this.Config.collectLifecycleData(this);

        String messageBody = "";

        Log.e(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.

        if (remoteMessage.getData().size() > 0) {

            Log.e(TAG, "Message data payload: " + remoteMessage.getData());

            //Read Message in payload as String to display in Notification

            messageBody = remoteMessage.getData().get("message");

        }

        // Check if message contains a notification payload.

        if (remoteMessage.getNotification() != null) {

            Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            //Read Message in Notification Body to display in Notification

            messageBody = remoteMessage.getNotification().getBody();

        }

        sendNotification(messageBody, remoteMessage);

    }

    private void handleNow() {

        Log.d(TAG, "Short lived task is done.");

    }

    @RequiresApi(api = Build.VERSION_CODES.O)

    private void sendNotification(String messageBody, RemoteMessage remoteMessage) {

        final String CHANNEL_ID = "channel_id_1";

        final String CHANNEL_NAME = "channel_name_1";

        NotificationManager mNotificationManager = (NotificationManager)

                getSystemService(Context.NOTIFICATION_SERVICE);

        Log.e("sendNotification", " in Messaging Service");

        Intent intent = new Intent(this, MainActivity.class);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,

                PendingIntent.FLAG_ONE_SHOT);

        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,

                CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);

        mNotificationManager.createNotificationChannel(notificationChannel);

        //put the data bundle in the intent to track clickthroughs

        intent.putExtra(messageBody, remoteMessage);

        String imageUri = remoteMessage.getData().get("attachment-url");

        bitmap = getBitmapfromUrl(imageUri);

        if (bitmap == null) {

            Log.e("true", "沒有圖片的");

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)

                    .setSmallIcon(R.drawable.ic_stat_ic_notification)

                    .setContentTitle("LawlietDevII")

                    .setContentText(messageBody)

                    .setAutoCancel(true)

                    .setSound(defaultSoundUri)

                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager =

                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

        } else {

            Log.e("else", "是有圖的喔");

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)

                    .setSmallIcon(R.drawable.ic_stat_ic_notification)

                    .setContentTitle("LawlietDevII")

                    .setContentText(messageBody)

                    .setAutoCancel(true)

                    .setSound(defaultSoundUri)

                    .setContentIntent(pendingIntent)

                    .setStyle(new NotificationCompat.BigPictureStyle()

                            .bigPicture(bitmap));

            NotificationManager notificationManager =

                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

        }

    }

    public Bitmap getBitmapfromUrl(String imageUrl) {

        try {

            URL url = new URL(imageUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);

            connection.connect();

            InputStream input = connection.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(input);

            return bitmap;

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            return null;

        }

    }

}

MyInstanceIDService.java

package com.example.lawlietlin.lawlietdevii;

import android.util.Log;

import com.adobe.mobile.Config;

import com.google.firebase.iid.FirebaseInstanceId;

import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**

     * Called if InstanceID token is updated. This may occur if the security of

     * the previous token had been compromised. Note that this is called when the InstanceID token

     * is initially generated so this is where you would retrieve the token.

     */

    // [START refresh_token]

    @Override

    public void onTokenRefresh() {

        // Get updated InstanceID token.

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or

        // manage this apps subscriptions on the server side, send the

        // Instance ID token to your app server.

        sendRegistrationToServer(refreshedToken);

    }

    // [END refresh_token]

    /**

     * Persist token to third-party servers.

     *

     * Modify this method to associate the user's FCM InstanceID token with any server-side account

     * maintained by your application.

     *

     * @param token The new token.

     */

    private void sendRegistrationToServer(String token) {

        // TODO: Implement this method to send token to your app server.

        Config.setPushIdentifier(token);

        Log.e("Token to Adobe: ", token);

    }

}

MyJobService.java

package com.example.lawlietlin.lawlietdevii;

import android.util.Log;

import com.firebase.jobdispatcher.JobParameters;

import com.firebase.jobdispatcher.JobService;

public class MyJobService extends JobService {

    private static final String TAG = "MyJobService";

    @Override

    public boolean onStartJob(JobParameters jobParameters) {

        Log.d(TAG, "Performing long running task in scheduled job");

        // TODO(developer): add long running task here.

        return false;

    }

    @Override

    public boolean onStopJob(JobParameters jobParameters) {

        return false;

    }

}

MainActivity.java

package com.example.lawlietlin.lawlietdevii;

import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.os.Build;

import android.support.annotation.NonNull;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import com.adobe.mobile.*;

import com.google.android.gms.tasks.OnCompleteListener;

import com.google.android.gms.tasks.Task;

import com.google.firebase.iid.FirebaseInstanceId;

import com.google.firebase.iid.InstanceIdResult;

import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

    //宣告全域變數.

    public TextView J_textView_Test;

    public EditText J_editText_Test;

    //

    private static final String TAG = "MainActivity";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //初始設定,您必須在主要活動的 onCreate 方法中呼叫一次以下方法:

        Config.setContext(this.getApplicationContext());

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        Log.e(TAG, "Token: " + refreshedToken);

        //findViewById.

        J_textView_Test = (TextView) findViewById(R.id.textView_Test);

        J_editText_Test = (EditText) findViewById(R.id.editText_Test);//editText_Test

        //傳回 Adobe Mobile 資料庫的目前版本。

        String libraryVersion = Config.getVersion();

        Log.e("傳回資料庫的目前版本:", libraryVersion);

        //追蹤狀態

        Analytics.trackState("首頁", null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // Create channel to show notifications.

            String channelId = getString(R.string.default_notification_channel_id);

            String channelName = getString(R.string.default_notification_channel_name);

            NotificationManager notificationManager =

                    getSystemService(NotificationManager.class);

            notificationManager.createNotificationChannel(new NotificationChannel(channelId,

                    channelName, NotificationManager.IMPORTANCE_LOW));

        }

        if (getIntent().getExtras() != null) {

            for (String key : getIntent().getExtras().keySet()) {

                Object value = getIntent().getExtras().get(key);

                Log.d(TAG, "Key: " + key + " Value: " + value);

            }

        }

        Button subscribeButton = findViewById(R.id.subscribeButton);

        subscribeButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Log.d(TAG, "Subscribing to news topic");

                // [START subscribe_topics]

                FirebaseMessaging.getInstance().subscribeToTopic("news")

                        .addOnCompleteListener(new OnCompleteListener<Void>() {

                            @Override

                            public void onComplete(@NonNull Task<Void> task) {

                                String msg = getString(R.string.msg_subscribed);

                                if (!task.isSuccessful()) {

                                    //msg = getString(R.string.msg_subscribe_failed);

                                }

                                Log.d(TAG, msg);

                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

                            }

                        });

            }

        });

        Button logTokenButton = findViewById(R.id.logTokenButton);

        logTokenButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                // Get token

                FirebaseInstanceId.getInstance().getInstanceId()

                        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {

                            @Override

                            public void onComplete(@NonNull Task<InstanceIdResult> task) {

                                if (!task.isSuccessful()) {

                                    Log.w(TAG, "getInstanceId failed", task.getException());

                                    return;

                                }

                                // Get new Instance ID token

                                String token = task.getResult().getToken();

                                // Log and toast

                                String msg = getString(R.string.msg_token_fmt, token);

                                Log.e(TAG, msg);

                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

                                J_textView_Test.setText("token=" + msg);

                                J_editText_Test.setText(msg);

                                Config.setPushIdentifier(token);

                            }

                        });

            }

        });

    }

    @Override

    public void onResume() {

        Config.collectLifecycleData(this);

        super.onResume();

    }

    @Override

    public void onPause() {

        Config.pauseCollectingLifecycleData();

        super.onPause();

    }

}

build.gradle

apply plugin: 'com.android.application'

android {

    compileSdkVersion 26

    defaultConfig {

        applicationId "com.example.lawlietlin.lawlietdevii"

        minSdkVersion 21

        targetSdkVersion 26

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}

dependencies {

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'com.android.support:appcompat-v7:26.1.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.2'

    implementation 'com.android.support:design:26.1.0'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'

    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.android.support:recyclerview-v7:26.1.0'

    //adobe library

    implementation files('libs/adobeMobileLibrary-4.16.0.jar')

    //加入Firebase SDK。

    implementation 'com.google.firebase:firebase-messaging:17.1.0'

    implementation 'com.google.firebase:firebase-core:16.0.1'

    implementation 'com.google.firebase:firebase-iid:16.2.0'

    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

    androidTestImplementation 'com.android.support.test:rules:1.0.2'

    androidTestImplementation 'com.android.support:support-annotations:27.1.1'

}

//加入Firebase SDK。

apply plugin: 'com.google.gms.google-services'

Replies

Highlighted

Avatar

Avatar

Jen_Andrews

Employee

Avatar

Jen_Andrews

Employee

Jen_Andrews
Employee

13-12-2018

Hi @lawlietl,

Are you still encountering issue with no tracking of opens of push notifications?

Jen