当程序并不是出在运行状态的时候,可以调用Notification来显示通知。
1、创建
Notification的创建主要涉及到三个类:NotificationManager,Notification和PendingIntent
NotificationManager主要是对通知进行管理。
Notification类主要用于对Notification的一些属性进行定义。获得的方式主要是通过兼容各个版本的support-v4中的NotificationCompat类来获得。
PendingIntent类可以理解成一个延迟执行的intent。
下面是一个实例代码:
public static final int NOTIFICATIONID = 0x101;
private NotificationManager notificationManager;
private NotificationCompat.Builder builder;
private Notification notification;
private PendingIntent pendingIntent;
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(NotificationManiActivity.this,null);
Intent intent = new Intent(NotificationManiActivity.this,NotificationTestActivity.class);
pendingIntent = PendingIntent.getActivity(NotificationManiActivity.this,0,intent,0);
notification =builder
.setContentTitle("通知标题")
.setContentText("通知内容")
.setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher)//Notification什么时候显示
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(NOTIFICATIONID,notification);
1.1 PendingIntent
PendingIntent的获得,可以调用自己的静态方法getActivity()、getBroadcast()、或者是getService()。参数都是一样的。第一个参数是Context,第二个参数是requestCode,第三个参数是intent。第四个参数是int类型的flag,可以分为以下四个值:FLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT,FLAG_UPDATE_CURRENT.分别解释为:
FLAG_ONE_SHOT:Flag indicating that this PendingIntent can be used only once表示此PendingIntent只能够使用一次。
FLAG_NO_CREATE:Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it. 定义的PendingIntent如果不存在,直接返回null,不去进行创建
FLAG_CANCEL