Android Notification详解——响应notification事件

上一篇讲了如何创建并显示一个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默认的就这样。

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

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

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

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

<activity android:name=".SubActivityl"
        android:launchMode="singleTask"
        android:taskAffinity=""
        android:excludeFromRecents="true">
</activity>
 

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

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

Intent[] makeIntentStack(Context context) {
	Intent[] intents = new Intent[2];
	intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, com.example.notificationtest.MainActivity.class));
	intents[1] = new Intent(context,  com.example.notificationtest.SubActivity.class);
	return intents;
}

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

接下来,创建并显示Notification:

void 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 a dinner tonight", 
			contentIntent);
	notification.flags |= Notification.DEFAULT_ALL;

	mNM.notify(1, notification);
}
 

猜你喜欢

转载自lovelydog.iteye.com/blog/1666340