You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击通知打开Activity时如何保留原有进度避免重新初始化

解决方案

问题根源:当前代码创建的Intent默认会生成全新的WorkoutActivity实例,触发onCreate生命周期重新初始化页面,原有运行中的实例和进度数据都会被覆盖。按照以下步骤修改即可:


步骤1:修改Intent配置,复用已有Activity实例

在创建跳转Intent时添加启动标记,让系统优先复用任务栈中已存在的WorkoutActivity实例,同时传入最新的运动进度数据,修改后的代码如下:

Intent open = new Intent(this, WorkoutActivity.class);
// 添加启动标记,复用已存在的Activity实例,不会重新创建
open.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 把当前最新的运动进度传入Intent,方便Activity更新UI
open.putExtra("current_distance", lastDistance);
open.putExtra("current_time", time);
open.putExtra("current_speed", speed);

// 兼容安卓12及以上版本,PendingIntent必须指定可变/不可变标记
PendingIntent openContent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
    openContent = PendingIntent.getActivity(this, 0, open, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
} else {
    openContent = PendingIntent.getActivity(this, 0, open, PendingIntent.FLAG_UPDATE_CURRENT);
}

// 以下原有通知构建代码无需修改
String nDistance = Double.toString(lastDistance);
String nSpeed = String.valueOf(speed);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.icon_logo_round)
            .setContentTitle(sWorkoutName.getText())
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Distance Covered : " + nDistance + " Kms" + '\n' + "Time : " + time + '\n' + "Speed : " + nSpeed + " km/hr"))
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(openContent);

notificationManager.notify(1, notification.build());

步骤2:在WorkoutActivity中接收进度数据更新UI

复用已有Activity实例时系统会回调onNewIntent方法,需要在该方法中读取传入的进度更新页面:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // 判断是否从通知跳转
    if (intent.hasExtra("current_distance")) {
        double distance = intent.getDoubleExtra("current_distance", 0d);
        long time = intent.getLongExtra("current_time", 0L);
        float speed = intent.getFloatExtra("current_speed", 0f);
        // 调用自定义方法更新页面的运动进度、时间、速度等UI
        updateWorkoutUI(distance, time, speed);
    }
}

如果WorkoutActivity已经被系统回收,也可以在onCreate方法中执行同样的Intent数据读取逻辑,恢复页面状态。


可选配置

也可以直接在AndroidManifest.xml中给WorkoutActivity固定启动模式,无需每次给Intent加标记:

<activity
    android:name=".WorkoutActivity"
    android:launchMode="singleTop" />

内容的提问来源于stack exchange,提问作者ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:54:01