如果 activity 已在运行,则在单击具有待定意图的通知时启动 activity 时将调用哪个函数

Which function will be called on starting an activity with a click on notification with a pending intent if the activity is already running

我想在用户单击通知时打开 activity。我可以使用挂起的意图来完成它,即使 activity 已经在运行,它也能正常工作。但是我想在点击操作上做一些事情。现在我在 onCreate 方法中这样做。它仅在 activity 未运行时有效。我尝试使用未达到上述条件的 onNewIntent 方法。我现在可以做什么?

在未决意图中使用 PendingIntent.FLAG_UPDATE_CURRENT 标志更新当前 activity。然后在 onResume()

中实现您的登录

NOTIFICATION_ID => 用于识别通知以进行进一步操作的数字。 mContext => 应用上下文。 结果Activity => Activity 待打开。

    //creating intent
    Intent resultIntent = new Intent(mContext, ResultActivity.class);
    resultIntent.putExtra("update_request", true);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //creating pending intent
    PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
        mContext,
        0,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );

    //Build the notification using Notification.Builder
    Notification.Builder builder = new Notification.Builder(mContext)
    .setSmallIcon(R.drawable.icon)
    .setAutoCancel(true)
    .setContentTitle("Title")
    .setContentIntent(resultPendingIntent)  //adding pending intent
    .setContentText("content");

    NotificationManager mNotificationManager =
   (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    //Get current notification
    Notification mNotification = builder.getNotification();

    //Show the notification
    mNotificationManager.notify(NOTIFICATION_ID, mNotification);

现在您可以对结果 activity 的 protected void onNewIntent(Intent intent) 函数进行操作。

您还可以将 activity 的新意图设置为 newIntent 函数中的 setIntent(intent)