Notification是Android系统中的一个特色功能。先看看Notification是怎么使用的。
首先需要一个NotificationManager来对通知进行管理,可以通过Context的getSystemService()方法获得。这里需要传入Context.NOTIFICATION_SERVICE就可以获得NotificationManager。接下来需要创建一个Notification对象,Notification对象是用来储存通知的各种信息的。以前的Andorid版本是通过直接构造的,即Notification notification = new Notification(); 现在一般不这样做了,使用Notification.Builder对象来创建Notification。
先来看基本notification的用法
public class NotificationActivity extends AppCompatActivity {
Button btn_notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
btn_notification = (Button) findViewById(R.id.btn_notification);
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("我的通知")//设置标题
.setContentText("通知消息")//设置消息内容
.setContentIntent(getDefault(Notification.FLAG_AUTO_CANCEL))//这是必须的东西,用来设置点击事件
.setTicker("有新的消息来了")//设置通知来了时候的提示
.setOngoing(false)
.setWhen(System.currentTimeMillis())//设置通知的时间
.setPriority(Notification.PRIORITY_DEFAULT)
.setDefaults(Notification.DEFAULT_ALL)//设置条件
.setSmallIcon(R.drawable.zhenji);//设置通知的图标
final Notification mNotification = builder.build();
//创建notification
btn_notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notificationManager.notify(1,mNotification);
}
});
}
public PendingIntent getDefault(int flag) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flag);
return pendingIntent;
}
}
Intent和pendingIntent的区别
pendingIntent可以用来启动活动,启动服务或者发送广播,这个和Intent非常相似,pendingIntent可以理解为延迟执行的Intent,获得PendingIntent的方法很简单,可以选择是getActivity()还是getService()或者是getBroadcast()
总结:notification的基本用法是很简单的,如果要添加点击事件或者携带参数,都可以在PendingIntent的第三个参数Intent中完成。