如何检查app是否在方法onMessageReceived()(FCM)中运行

时间:2017-03-21 08:35:47

标签: android

我已经实现了发送推送通知的所有机制。

我的应用响应点击推送消息未修复。 也就是说,当用户单击该消息时,我的应用程序(背景或前景)的状态决定下一步。

如您所知,在收到推送消息时调用方法onMessageReceived()(即使屏幕关闭)

所以,我想插入一些代码来检查应用程序是onMessageReceived()中的前景还是后台。

以下是我的代码:

public void onMessageReceived(RemoteMessage remoteMessage) {
    String body = remoteMessage.getData().get("body");
    title = remoteMessage.getData().get("title");

    sendNotification(body);
    if(remoteMessage.getData().size() > 0){

    }
}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, Activity_CreateAccount.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.intro_logo)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setPriority(Notification.PRIORITY_MAX);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    PowerManager pm = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);

    PowerManager.WakeLock wakeLock =
            pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "");


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

    wakeLock.acquire();

    if(wakeLock!=null){
        wakeLock.release();
        wakeLock = null;
    }
}

1 个答案:

答案 0 :(得分:5)

如@quicklearner所述,您需要添加活动生命周期回调(手动)。

可以找到相同的好帖子here

总结:

  1. 创建自定义应用程序类,扩展Application
  2. 并添加以下方法,如下所示:

    public class MyApplication extends Application {
    
      public static boolean isActivityVisible() {
        return activityVisible;
      }  
    
      public static void activityResumed() {
        activityVisible = true;
      }
    
      public static void activityPaused() {
        activityVisible = false;
      }
    
      private static boolean activityVisible;
    }
    
    1. 同时将其添加到清单文件中,如帖子

    2. 所示
    3. 然后,无论您想检查哪项活动,

    4. 在该活动的onResume方法内

      调用

      MyApplication.activityResumed();

      并在onPause电话

      MyApplication.activityPaused();

      1. 检查状态并执行基于逻辑的操作
      2. MyApplication.isActivityVisible()

        归功于SO帖子!