美文网首页
Android TaskStackBuilder在Notific

Android TaskStackBuilder在Notific

作者: hahaYXXXJ | 来源:发表于2017-10-20 11:56 被阅读66次

首先是用一般的PendingIntent来进行跳转

mBuilder=newNotificationCompat.Builder(this).setContent(view)          .setSmallIcon(R.drawable.icon).setTicker("新资讯")          .setWhen(System.currentTimeMillis())          .setOngoing(false)          .setAutoCancel(true);Intentintent=newIntent(this,NotificationShow.class);PendingIntentpendingIntent=PendingIntent.getActivity(this,0,  intent,PendingIntent.FLAG_UPDATE_CURRENT);  mBuilder.setContentIntent(pendingIntent);

这里是直接用PendingIntent来跳转到NotificationShow。

在运行效果上来看,首先发送了一条Notification到通知栏上,然后这时,退出程序,即MainActivity已经不存在了,回到home主菜单,看到Notification仍然存在,当然,我们还没有点击或者cancel它,现在去点击Notification,跳转到NotificationShow界面,然后我们按下Back键,发现直接回到home菜单了。现在大多数android应用都是在通知栏中如果有Notification通知的话,点击它,然后会直接跳转到对应的应用程序的某个界面,这时如果回退,即按下Back键,会返回到该应用程序的主界面,而不是系统的home菜单。所以用上面这种PendingIntent的做法达不到目的。这里我们使用TaskStackBuilder来做。

mBuilder=newNotificationCompat.Builder(this).setContent(view)                  .setSmallIcon(R.drawable.icon).setTicker("新资讯")                  .setWhen(System.currentTimeMillis())                  .setOngoing(false)                  .setAutoCancel(true);Intentintent=newIntent(this,NotificationShow.class);TaskStackBuilderstackBuilder=TaskStackBuilder.create(this);          stackBuilder.addParentStack(NotificationShow.class);          stackBuilder.addNextIntent(intent);PendingIntentpendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,//intent, PendingIntent.FLAG_UPDATE_CURRENT);mBuilder.setContentIntent(pendingIntent);

显示用TaskStackBuilder.create(this)创建一个stackBuilder实例,接下来addParentStack();

关于这个方法,我们查一下官方API文档:

Add the activity parent chain as specified by the parentActivityName attribute of the activity (or activity-alias) element in the application's manifest to the task stack builder

这句话意思是:为跳转后的activity添加一个父activity,在activity中的manifest中添加parentActivityName即可。

<activity

android:name="com.lvr.service.NotificationShow"

android:parentActivityName=".MainActivity">

</activity>

这里我让它的parentActivity为MainActivity,也就是说在NotificationShow这个界面点击回退时,会跳转到MainActivity这个界面,而不是像上面一样直接回到了home菜单。

相关文章

网友评论

      本文标题:Android TaskStackBuilder在Notific

      本文链接:https://www.haomeiwen.com/subject/knamuxtx.html