如何处理已经 运行 activity 中的 PendingIntent

How do I process PendingIntent in already running activity

我有一个小应用程序,其中主要 activity 已经在前面,并且可能会显示一条通知。当用户点击通知时,我想让主要的 activity 获得额外的意图并对其采取行动,但不确定如何,因为它已经 运行.

我的代码表示 returns PendingInent 用于 NotificationCompat.Builder:

private static PendingIntent getPendingIntent(Context ctx, String brandId) {
    Intent showIntent = new Intent(ctx, MainActivity.class);
    showIntent.setAction(Intent.ACTION_MAIN);
    showIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    showIntent.putExtra(PUSH_NOTIFICATION, true);
    showIntent.putExtra(BRAND_ID, brandId);

    return PendingIntent.getActivity(ctx, 0, showIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

我以为我的 MainActivity 可能会重新启动,但事实并非如此

我该怎么做?

做这样的事情 onResume()....{ if(intent.getExtras().get("your_required_thing")!=null){ // do your stuff} 否则你不能也使用 broadCastReceiver 并在 onResume 中注册接收者......并在 onReceive 获得额外的意图广播

您是否尝试过在 MainActivity class 中覆盖 "onNewIntent" 方法?

例如:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    //handle new intent here
}

因为您的 activity 已经 运行,新的意图应该出现在这里。

private static PendingIntent getPendingIntent(Context ctx, String brandId) {
    Intent showIntent = new Intent(ctx, MainActivity.class);
    showIntent.setAction(Intent.ACTION_MAIN);
    showIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    showIntent.putExtra(PUSH_NOTIFICATION, true);
    showIntent.putExtra(BRAND_ID, brandId);
return PendingIntent.getBroadcast(this, 0, showIntent, 0);;
}

然后创建广播class

public static class myNotificationCloseButtonHandler extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Close Clicked", Toast.LENGTH_SHORT).show();
            Intent startIntent = new Intent(context, PlayerForegroundService.class);
            startIntent.setAction(PlayerForegroundService.STOP_FOREGROUND_ACTION);
            context.startService(startIntent);
        }


}