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

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

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

通知跳转Activity的实现

为了实现类似Gmail的行为,我们需要在应用中定义两个Activity:ParentActivity和SubActivity。当通知点击后,跳转到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栈管理:通过makeRestartActivityTask和getActivities方法,确保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/

你可能感兴趣的文章
python3 mysql8_Python MySQL8.0 错误:authentication plugin 'calling_sha2_password' is not supported....
查看>>
Python关键代码总览!从Zero到Hero必看的考点
查看>>
python3 robotframework+pycharm框架搭建
查看>>
Python3 shutil模块
查看>>
Python关于strftime函数详细解析 附实战代码
查看>>
Python3 tutorial day3
查看>>
python3 week4
查看>>
Python3 创建数组
查看>>
python3 套接字异常(a byte-like object is required not str)
查看>>
python3 实现用户三次输入错误记录黑名单并对该用户登录锁定-day1
查看>>
python3 文本变图片
查看>>
Python3 查看 com 组件的属性
查看>>
python3 案例分享--发邮件
查看>>
python3 模板库_Python3 标准库概览_Python教程_我爱模板网 - 提供下载各种免费建站资源,免费网站模板,免费网页特效,让你爱上建站!...
查看>>
Python3 求最大/小值及索引值 Numpy
查看>>
python3+django使用celery执行某些任务失败的解决方案
查看>>
Python3+Requests+Unittest实战系列【一】
查看>>
python3+requests+unittest实战系列【一】
查看>>
python3+requests+unittest实战系列【二】
查看>>
Python3+Requests+Unittest实战系列【二】
查看>>