有没有办法在接收推送通知时将应用程序置于前台?

Rah*_*raj 5 android state push-notification android-activity firebase

例如在 WhatsApp 中。当我打电话给某人时,即使该应用程序在后台或被杀死,活动也会打开。我该如何实施?此外,我不希望我的应用程序启动新活动,因为此应用程序将在受控环境中使用。我的应用程序将始终在后台。当应用程序打开(后台或前台)时,用户将收到通知,因此当他们收到此通知时,他们的应用程序应自动应用程序(不是启动新活动),而只是将当前活动推送到前台。

为了最好地理解这就是我想要实现的:用户 A 打开应用程序,然后将其最小化。所以现在他有资格接收通知。该应用程序当前在 Activity A 上。当用户收到通知时,我们将收到的数据推送到列表中并将其显示在 Activity A 上。我想要做的就是当用户 A 收到推送通知时将 Activity A 推送到前台不要再次创建 Activity A 或任何类似的东西,而只是将其置于前台。任何帮助将非常感激。谢谢!

Kha*_*ela 0

收到消息后,启动NotificationActivity将检查您的应用程序是否已在运行,然后finish 该活动将为您带来堆栈上最后打开的活动,如果应用程序未运行,将启动您的应用程序MainActivity

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

     // Check if message contains a data payload.
       if (remoteMessage.getData().size() > 0) {
         Log.d(TAG, "Message data payload: " + remoteMessage.getData());
       }

     // Check if message contains a notification payload.
      if (remoteMessage.getNotification() != null) {
          startActivity(new Intent(this , NotificationActivity.class));
        }  
     }


public class NotificationActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        // If this activity is the root activity of the task, the app is not running
        if (isTaskRoot())
        {
            // Start the app before finishing
            Intent startAppIntent = new Intent(getApplicationContext(), MainActivity.class);
            startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startAppIntent);
        }

      // Now finish, which will drop the user in to the activity that was at the top of the task stack
        finish();
    }
}
Run Code Online (Sandbox Code Playgroud)

检查此 答案和此答案以获取更多详细信息。