点击通知后如何正确地将新 Activity 添加到堆栈顶部

How to properly add new Activity onto top of the stack after tapping notification

我正在编写一个包含大量活动的非常大的应用程序。我有一个 class 运行 在后台检查服务器上是否有任何更改并执行适当的操作。其中一项操作是向用户发送有关员工上班、下班和类似情况的通知。这种通知是可点击的,它应该会打开员工的联系页面 PeopleSingleScene_Activity,并且按预期工作。但是,当我单击后退按钮时,应用程序退出(没有父活动)。

创建带有未决意图的通知的代码如下:

public void sendEmployeeWorkNotification(String ticker, String title, String text, String loc, int employee_id) {
    PendingIntent pendingIntent;
    Intent intent;
    Context currentContext = G.context;

    if (loc.equals("LOC")) {
        intent = new Intent(currentContext, PeopleSingleScene_Activity.class);
        intent.putExtra("people_id", employee_id);
        pendingIntent = PendingIntent.getActivity(currentContext, 0, intent, 0);
    } else {
        //some other actions
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(currentContext, CHANNEL_ID)
        .setSmallIcon(R.drawable.vector_notif)
        .setTicker(ticker)
        .setContentTitle(title)
        .setContentText(text)
        .setColor(ContextCompat.getColor(currentContext, R.color.rcOutcome))
        .setStyle(new NotificationCompat.BigTextStyle()
                .bigText(text))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(currentContext);

    notificationManager.notify(G.simpleMessageCounter, builder.build());
    simpleSong(R.raw.notificationsimple);
    G.simpleMessageCounter++;
}

G.context 是最后打开的 activity 上下文...它是全局 class G 中的静态变量。我正在以某种方式创建它:

public class SomeActivityClass extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.some_layout);
        G.context = this;
        ....
    }
    ....
}

我还尝试使用我的应用 class 中的上下文来检索字符串值或任何其他在 classes 中没有活动的上下文...

public class App extends Application {
    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }

    public static String getStr(int resid) {
        return mContext.getResources().getString(resid);
    }
}

当我从 App.getContext(); 使用此上下文时,结果是一样的,在点击后退按钮后,应用程序退出。

问题是:创建待定意图和通知的上下文是否存在问题,或者意图创建标志是否存在问题?我尝试了很多与上下文和标志的组合,但其中 none 有效。而且我不能在每个 activity 上写(或者我不知道)一些监听器来监听这种事件并从自身打开新的意图。将有超过 50 个活动...

您必须为此 activity 单顶设置启动模式 <activity android:launchMode="singleTop" />

阅读更多关于 Android Activity Launch Mode

终于找到解决办法了,感谢我的好友 Miljan。

创建 pendingIntent 时,只需要一个适当的标志。所以而不是

pendingIntent = PendingIntent.getActivity(currentContext, 0, intent, 0);

只要放一个标志

pendingIntent = PendingIntent.getActivity(currentContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);

而且它正常工作。在显示通过点击通知启动的 activity 后,我可以返回到之前的 activity。