我想在用户点击通知时打开一个 Activity 。我可以使用挂起的 Intent 来完成它,即使 Activity 已经在运行,它也能正常工作。但是我想在点击操作上做一些事情。现在我在 onCreate
方法中这样做。它仅在 Activity 未运行时有效。我尝试使用未达到上述条件的 onNewIntent
方法。我现在可以做什么?
最佳答案
NOTIFICATION_ID => 用于识别通知以进行进一步操作的编号。 mContext => 应用上下文。 ResultActivity => 要打开的 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);
现在您可以对 Resulting Activity 的 protected void onNewIntent(Intent intent)
函数执行操作。
您还可以通过 newIntent
函数将新 Intent 设置为 Activity 的 Intent ,如 setIntent(intent)
。
关于android - 如果 Activity 已经在运行,则通过单击具有待定 Intent 的通知来启动 Activity 时将调用哪个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27794098/