当通知点击后应用程序未在堆栈上打开时在android中不起作用

Posted

技术标签:

【中文标题】当通知点击后应用程序未在堆栈上打开时在android中不起作用【英文标题】:when app is not open on stack after notification click not working in android 【发布时间】:2020-02-13 04:52:05 【问题描述】:

enter image description here

类路径'com.google.gms:google-services: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'

MyFirebaseInstanceIDService.java

公共类 MyFirebaseInstanceIDService 扩展 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();

MyFirebaseMessagingService.java

公共类 MyFirebaseMessagingService 扩展 FirebaseMessagingService

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();
    

【问题讨论】:

【参考方案1】:

我认为问题出在else 条件下

resultIntent = new Intent(this, NavigationActivity.class);
taskStackBuilder.addParentStack(NavigationActivity.class);
taskStackBuilder.addNextIntentWithParentStack(resultIntent);

您正在设置Parent 并在通知点击时打开活动相同。所以它不遵循TaskStackBuilder 的后栈架构。

您能否纠正父母并尝试一下希望这会奏效。

【讨论】:

@ForamShah 我已经更新了答案,你也可以检查一下。 不,仍然无法正常工作。当我在 androidx 中迁移整个项目并更新 Dependencies 版本并使用 FirebaseInstanceIDService 的 FirebaseMessagingService 实例时,会引发此问题。因为 handleIntent lmethod 不在新版本中

以上是关于当通知点击后应用程序未在堆栈上打开时在android中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

iOS - 打开时应用程序徽章消失

仅当我在新选项卡上打开时才会打开 KnockoutJs 链接

react native - 应用程序被杀死/未启动时未收到通知

Flutter:当应用程序处于后台但未在 iOS 中终止时,无法在通知单击时重定向到特定屏幕

在 Nexus Player、Android Cordova 应用程序上打开时输入第一个字符的虚拟键盘

当用户点击通知时,Activity 没有打开