1. 概述
可以在一个应用中发出一个Notification,而当用户查看/单击这个Notification的时候,去执行进一步的动作。主要涉及如下几个class:
- Intent:包含执行动作的目标组件名称
- PendingIntent:进一步封装intent对象,并作为Notification的数据
- Notification:对应通知栏的Notification对象;
- NotificationManager:调用notify()方法,发出一个通知消息到通知栏
2. 示例
这个例子有两个应用,其中一个(HelloNotificationSender)生成notification对象;当用户单击这个notification的时候,再打开第二个应用(HelloNotificationReceiver)。
2.1 代码
如下:
package com.example.hellonotificationsender;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sender_main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendNotification();
}
});
}
private void sendNotification() {
Intent intent = new Intent();
ComponentName component = new ComponentName(
"com.example.hellonotificationreceiver",
"com.example.hellonotificationreceiver.MainActivity");
intent.setComponent(component);
int requestCode = 0;
int flags = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, flags);
String tickerText = "ticker text";
CharSequence contentTitle = "content title";
CharSequence contentText = "content text";
Notification notification = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis());
notification.setLatestEventInfo(this, contentTitle, contentText, pendingIntent);
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
final int NOTIFICATION_REF = 1;
notificationManager.notify(NOTIFICATION_REF, notification);
}
}
2.2 效果
一闪而过的ticker:
通知栏出现了对应的图标(左上角):
下拉通知栏可以看到更详细的信息:
3. 选项讨论
3.1 Notification.defaults
当生成Notification的时候,可以设置振动、铃声等效果。为此,可以在上面代码的基础上增加下面几行进行效果验证:
notification.defaults = Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE;
3.2 Notification.flags
上面例子生成的notification会一直存在,即便单击它启动了新的应用,也不会消失掉,这和通常使用的大多数的notification是不一样的。为此,可以验证如下的代码:
notification.flags = notification.flags
//| Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_INSISTENT
| Notification.FLAG_ONLY_ALERT_ONCE
| Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_SHOW_LIGHTS
;
4. 其他
其它一些方面:
- Notification的tray ui也可以定制;
- 新版本的Android推荐使用Notification.Builder来创建Notification对象、设置各种属性。