Java 当应用程序在收到通知后未在堆栈上打开时,单击“不在android中工作”

Java 当应用程序在收到通知后未在堆栈上打开时,单击“不在android中工作”,java,android,push-notification,firebase-cloud-messaging,androidx,Java,Android,Push Notification,Firebase Cloud Messaging,Androidx,classpath'com.google.gms:googleservices:4.3.3' 添加依赖项 implementation 'com.google.firebase:firebase-auth:19.2.0' implementation 'com.google.firebase:firebase-core:17.2.2' implementation 'com.google.firebase:firebase-crash:16.2.1' implementation 'com.g

classpath'com.google.gms:googleservices:4.3.3'

添加依赖项

 implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.0'
implementation 'com.google.firebase:firebase-analytics:17.2.2'

implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.gms:play-services-tagmanager:17.0.0'
MyFireBaseInstancedService.java

公共类MyFireBaseInstancedService扩展了FirebaseMessagingService{

private static final String TAG = "MyFirebaseIIDService";
public static String fcm_Tocken ;


@Override
public void onNewToken(@NonNull String s) {
    super.onNewToken(s);

    storeRegIdInPref(s);

    // sending reg id to your server
    sendRegistrationToServer(s);

    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(CONSTANTS.REGISTRATION_COMPLETE);
    registrationComplete.putExtra("token", s);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);


    String refreshedToken =  FirebaseInstanceId.getInstance().getToken();
    FirebaseMessaging.getInstance().subscribeToTopic("all");
    SharedPreferences.Editor editor1 = getSharedPreferences(CONSTANTS.API_param_DeviceToken, MODE_PRIVATE).edit();
    editor1.putString(CONSTANTS.API_param_DeviceToken,refreshedToken); //Friend
    editor1.apply();
    editor1.commit();
    fcm_Tocken = refreshedToken;
}
private void sendRegistrationToServer(final String token) {
    // sending gcm token to server
    Log.e(TAG, "sendRegistrationToServer: " + token);
}

private void storeRegIdInPref(String token) {
    SharedPreferences.Editor editor1 = getSharedPreferences(CONSTANTS.API_param_DeviceToken, MODE_PRIVATE).edit();
    editor1.putString(CONSTANTS.API_param_DeviceToken,token); //Friend
    editor1.apply();
    editor1.commit();
}
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private NotificationManager mNotificationManager;
private NotificationCompat.Builder notificationBuilder;
Activity context;
String title = "", image = "", message = "", flag = "", id = "";

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    FirebaseMessaging.getInstance().subscribeToTopic("topic");

    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;
    if (remoteMessage == null)
        return;
    if (remoteMessage.getNotification() != null) {

        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        title = remoteMessage.getNotification().getTitle();
        message = remoteMessage.getNotification().getBody();
        sendNotification(title, message, flag, id, String.valueOf(m));
    }
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            title = remoteMessage.getData().get("title");
            image = remoteMessage.getData().get("image");
            message = remoteMessage.getData().get("body");
            flag = remoteMessage.getData().get("flag");
            id = remoteMessage.getData().get("id");
            sendNotification(title, message, flag, id, String.valueOf(m));

        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void sendNotification(String title, String message, String flag, String id, String m) {

    Intent resultIntent= null;
    PendingIntent resultPendingIntent=null;
    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
    try {
        if (flag != null && flag.equalsIgnoreCase("refer_friend")) {
            resultIntent = new Intent(this, SquareEarnActivity.class);
            resultIntent.putExtra(CONSTANTS.back_flag, CONSTANTS.FLAG_ONE);
            taskStackBuilder.addParentStack(NavigationActivity.class);
            taskStackBuilder.addNextIntentWithParentStack(resultIntent);
            resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        }else
            resultIntent = new Intent(this, NavigationActivity.class);
            taskStackBuilder.addParentStack(NavigationActivity.class);
            taskStackBuilder.addNextIntentWithParentStack(resultIntent);
            resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel("ID", "NAME", NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("Notification");
            notificationManager.createNotificationChannel(channel);

            notificationBuilder = new NotificationCompat.Builder(this, channel.getId());
        } else {
            notificationBuilder = new NotificationCompat.Builder(this);
        }

        notificationBuilder.setSmallIcon(R.drawable.logo);
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setContentText(message);
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS
                | Notification.FLAG_AUTO_CANCEL);
        notificationBuilder.setColor(getResources().getColor(R.color.darkorange));
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSound(defaultSoundUri);
        notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        notificationBuilder.setContentIntent(resultPendingIntent);

        Notification note = notificationBuilder.build();
        note.flags = Notification.FLAG_INSISTENT;
        note.flags = Notification.DEFAULT_VIBRATE;
        note.flags = Notification.DEFAULT_SOUND;
        note.flags = Notification.DEFAULT_LIGHTS;
        note.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(Integer.parseInt(m), notificationBuilder.build());

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

MyFirebaseMessagingService.java

公共类MyFirebaseMessagingService扩展了FirebaseMessagingService{

private static final String TAG = "MyFirebaseIIDService";
public static String fcm_Tocken ;


@Override
public void onNewToken(@NonNull String s) {
    super.onNewToken(s);

    storeRegIdInPref(s);

    // sending reg id to your server
    sendRegistrationToServer(s);

    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(CONSTANTS.REGISTRATION_COMPLETE);
    registrationComplete.putExtra("token", s);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);


    String refreshedToken =  FirebaseInstanceId.getInstance().getToken();
    FirebaseMessaging.getInstance().subscribeToTopic("all");
    SharedPreferences.Editor editor1 = getSharedPreferences(CONSTANTS.API_param_DeviceToken, MODE_PRIVATE).edit();
    editor1.putString(CONSTANTS.API_param_DeviceToken,refreshedToken); //Friend
    editor1.apply();
    editor1.commit();
    fcm_Tocken = refreshedToken;
}
private void sendRegistrationToServer(final String token) {
    // sending gcm token to server
    Log.e(TAG, "sendRegistrationToServer: " + token);
}

private void storeRegIdInPref(String token) {
    SharedPreferences.Editor editor1 = getSharedPreferences(CONSTANTS.API_param_DeviceToken, MODE_PRIVATE).edit();
    editor1.putString(CONSTANTS.API_param_DeviceToken,token); //Friend
    editor1.apply();
    editor1.commit();
}
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private NotificationManager mNotificationManager;
private NotificationCompat.Builder notificationBuilder;
Activity context;
String title = "", image = "", message = "", flag = "", id = "";

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    FirebaseMessaging.getInstance().subscribeToTopic("topic");

    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;
    if (remoteMessage == null)
        return;
    if (remoteMessage.getNotification() != null) {

        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        title = remoteMessage.getNotification().getTitle();
        message = remoteMessage.getNotification().getBody();
        sendNotification(title, message, flag, id, String.valueOf(m));
    }
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            title = remoteMessage.getData().get("title");
            image = remoteMessage.getData().get("image");
            message = remoteMessage.getData().get("body");
            flag = remoteMessage.getData().get("flag");
            id = remoteMessage.getData().get("id");
            sendNotification(title, message, flag, id, String.valueOf(m));

        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void sendNotification(String title, String message, String flag, String id, String m) {

    Intent resultIntent= null;
    PendingIntent resultPendingIntent=null;
    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
    try {
        if (flag != null && flag.equalsIgnoreCase("refer_friend")) {
            resultIntent = new Intent(this, SquareEarnActivity.class);
            resultIntent.putExtra(CONSTANTS.back_flag, CONSTANTS.FLAG_ONE);
            taskStackBuilder.addParentStack(NavigationActivity.class);
            taskStackBuilder.addNextIntentWithParentStack(resultIntent);
            resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        }else
            resultIntent = new Intent(this, NavigationActivity.class);
            taskStackBuilder.addParentStack(NavigationActivity.class);
            taskStackBuilder.addNextIntentWithParentStack(resultIntent);
            resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel("ID", "NAME", NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("Notification");
            notificationManager.createNotificationChannel(channel);

            notificationBuilder = new NotificationCompat.Builder(this, channel.getId());
        } else {
            notificationBuilder = new NotificationCompat.Builder(this);
        }

        notificationBuilder.setSmallIcon(R.drawable.logo);
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setContentText(message);
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS
                | Notification.FLAG_AUTO_CANCEL);
        notificationBuilder.setColor(getResources().getColor(R.color.darkorange));
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSound(defaultSoundUri);
        notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        notificationBuilder.setContentIntent(resultPendingIntent);

        Notification note = notificationBuilder.build();
        note.flags = Notification.FLAG_INSISTENT;
        note.flags = Notification.DEFAULT_VIBRATE;
        note.flags = Notification.DEFAULT_SOUND;
        note.flags = Notification.DEFAULT_LIGHTS;
        note.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(Integer.parseInt(m), notificationBuilder.build());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

我认为问题出在
其他
条件下

resultIntent = new Intent(this, NavigationActivity.class);
taskStackBuilder.addParentStack(NavigationActivity.class);
taskStackBuilder.addNextIntentWithParentStack(resultIntent);
您正在设置
Parent
,并在通知点击相同的按钮时打开活动。因此,它没有遵循
TaskStackBuilder
的后堆栈体系结构


你能纠正家长的错误并尝试一下吗?希望这能奏效。

@ForamShah我已经更新了答案。你能检查一下吗。不行,仍然不行。当我在androidx中迁移整个项目并更新依赖项版本并使用FirebaseInstancedService的FirebaseMessagingService实例时,会出现此问题。因为HandleContent lmethod不在新版本中