分享

Android Notification详解

 天海544 2014-08-04

上一篇讲了如何创建并显示一个notification,这一篇就总结下点击notification后,程序应该如何响应。

 

一般来讲,点击一个notification后,都会打开一个Activity做为对点击事件的响应,这个Activity是之前在PendingIntent中设置好的。

经常玩Android手机的应该都有印象,在日历应用中,你新建一个提醒,当提醒通知收到后,你点击通知,会进入提醒的内容页面,如果这个时候按back键,会直接退出应用。

但是在Gmail的应用中,如果有一封新邮件到来,那么点击通知后,会进入到邮件的内容页面,等你看完邮件,点击back键,会退到邮件列表页面,再按back键,才会退出应用。

 

我们总结一下两种情况,假设我们的应用有两个Activity(ParentActivity、SubActivity),notification中设置打开的Activity为SubActivity。

那么第一种情况就是:

点击Notification ——>进入SubActivity ——> back键 ——> 退出应用

第二种情况:

点击Notification ——>进入SubActivity ——> back键 ——> 退到ParentActivity ——>back键 ——>退出应用

 

第一种情况比较简单,只需要在PendingIntent中指定Activity,不需要其他设置,Android默认的就这样。

 

Java代码  收藏代码
  1. PendingIntent contentIntent = PendingIntent.getActivity(context, 0,  intent, PendingIntent.FLAG_CANCEL_CURRENT);  

但是在创建PendingIntent的时候需要注意参数PendingIntent.FLAG_CANCEL_CURRENT

这个标志位用来指示:如果当前的Activity和PendingIntent中设置的intent一样,那么久先取消当前的Activity,用PendingIntent中指定的Activity取代之。

另外,需要在Manifest中对指定的Activity设置属性

 

Java代码  收藏代码
  1. <activity android:name=".SubActivityl"  
  2.         android:launchMode="singleTask"  
  3.         android:taskAffinity=""  
  4.         android:excludeFromRecents="true">  
  5. </activity>  
 

 

第二种情况稍微复杂点,因为如果只打开一个SubActivity,程序并没办法知道他的上一级Activity是谁,所以需要在点击Notification时打开一组Activity,但是我们并不需要一个个去调用startActivity方法,PendingIntent提供了个静态方法getActivities,里面可以设置一个Intent数组,用来指定一系列的Activity。

所以我们首先写一个函数创建一个Activity数组:

 

Java代码  收藏代码
  1. Intent[] makeIntentStack(Context context) {  
  2.     Intent[] intents = new Intent[2];  
  3.     intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, com.example.notificationtest.MainActivity.class));  
  4.     intents[1] = new Intent(context,  com.example.notificationtest.SubActivity.class);  
  5.     return intents;  
  6. }  

 

 其中需要注意的是Intent.makeRestartActivityTask方法,这个方法用来创建activity栈的根activity

接下来,创建并显示Notification:

 

Java代码  收藏代码
  1. void showNotification(Intent intent) {  
  2.     Notification notification = new Notification(  
  3.             R.drawable.status_icon,   
  4.             "Hello World ticker text",  
  5.             System.currentTimeMillis());  
  6.   
  7.     PendingIntent contentIntent = PendingIntent.getActivities(  
  8.             this,  
  9.             0,  
  10.             makeIntentStack(this),   
  11.             PendingIntent.FLAG_CANCEL_CURRENT);  
  12.     notification.setLatestEventInfo(  
  13.             this,   
  14.             "Title",  
  15.             "Hey, shall we have a dinner tonight",   
  16.             contentIntent);  
  17.     notification.flags |= Notification.DEFAULT_ALL;  
  18.   
  19.     mNM.notify(1, notification);  
  20. }  
 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多