博客
关于我
android-Notification点击跳转Activity
阅读量:98 次
发布时间:2019-02-26

本文共 1981 字,大约阅读时间需要 6 分钟。

在Android应用中,当通知通知用户点击后,用户通常会按返回键退出应用。但在Gmail等应用中,由于需要在邮件列表页面再次点击返回键才能退出,这种设计可能会影响用户体验。

通知跳转Activity的实现

为了实现类似Gmail的行为,我们需要在应用中定义两个Activity:ParentActivitySubActivity。当通知点击后,跳转到SubActivity,按返回键后,系统会退回到ParentActivity,再按返回键才能退出应用。

实现方法

1. 简单场景

在这种简单场景中,我们只需要在PendingIntent中指定SubActivity。默认情况下,Android系统会将当前的Activity替换为新的Activity。

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

2. 复杂场景

如果需要退回到ParentActivity,我们需要在PendingIntent中设置多个跳转目标。我们可以使用getActivities()方法来指定一系列目标Activity。

Intent[] intents = new Intent[2];intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, MainActivity.class));intents[1] = new Intent(context, SubActivity.class);PendingIntent contentIntent = PendingIntent.getActivities(context, 0, intents, PendingIntent.FLAG_CANCEL_CURRENT);

注意事项

  • FLAG_CANCEL_CURRENT:如果当前Activity和PendingIntent中的intent相同,会取消当前的Activity,并使用PendingIntent中的目标Activity替换。
  • Manifest配置:确保指定的Activity在AndroidManifest中定义,并设置android:launchMode="singleTask"android:taskAffinity="",以避免多次启动同一个Activity。
  • Activity栈管理:通过makeRestartActivityTaskgetActivities方法,确保Activity栈能够正确管理,防止重复或错误的跳转。

示例代码

// 创建Activity数组Intent[] makeIntentStack(Context context) {    Intent[] intents = new Intent[2];    intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, MainActivity.class));    intents[1] = new Intent(context, SubActivity.class);    return intents;}// 创建并显示Notificationvoid showNotification(Intent intent) {    Notification notification = new Notification(R.drawable.status_icon, "Hello World ticker text", System.currentTimeMillis());    PendingIntent contentIntent = PendingIntent.getActivities(this, 0, makeIntentStack(this), PendingIntent.FLAG_CANCEL_CURRENT);    notification.setLatestEventInfo(this, "Title", "Hey, shall we have dinner tonight?", contentIntent);    notification.flags |= Notification.DEFAULT_ALL;    mNM.notify(1, notification);}

通过以上方法,我们可以实现类似Gmail的通知跳转场景,确保用户按返回键后能够正确退回到ParentActivity。

转载地址:http://nusk.baihongyu.com/

你可能感兴趣的文章
python | alabaster,一个强大的 关于alabaster 主题 Python 库!
查看>>
python | algorithms,一个超赞的 集合常用算法的Python 库!
查看>>
python调用jpype 报错:OSError JVM is already started和JVM cannot be restarted
查看>>
python | authlib,一个强大的 Python 库!
查看>>
python | awswrangler,一个高效的 Python 库!
查看>>
python | bashplotlib,一个有趣的Python库!
查看>>
python | bentoml,一个超级厉害的 模型部署 Python 库!
查看>>
python调用jar包的模块_python调用jar包
查看>>
python | black,一个神奇的 代码格式化工具 Python 库!
查看>>
python | bleach,一个超强的 Python 库!
查看>>
python | cartopy,一个有趣的 Python 库!
查看>>
python | cloud-init,一个实用的 云计算 Python 库!
查看>>
python | code2flow,一个神奇的 Python 库!
查看>>
python | cudf,一个超实用的 Python 库!
查看>>
python | daphne,一个非常nice的 Python 库!
查看>>
python调用halcon
查看>>
python | doit,一个非常实用的 Python 库!
查看>>
python | easyocr,一个超厉害的 关于OCR的 Python 库!
查看>>
python | fastFM,一个高级的 Python 库!
查看>>
python | feature_engine,一个实用的 Python 库!
查看>>