安卓O之后google更新了notification的API,下面是一个例子,这个例子里面涵盖的内容有
1.通知的自动取消
2.通知的点击事件
3.通知的更新
4.通知的取消
/**
* type==0 stop notification; type==1 go to saved path
* @param type
*/
@TargetApi(Build.VERSION_CODES.O)
private void showNotification(int type) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelID = getPackageName() + NOTIFICATION_ID;
NotificationChannel channel = new NotificationChannel(channelID, "screen_recorder", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent();
boolean stop = type == 0;
if (stop) {
intent.setClass(this, ScreenRecordingActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("status", false);
} else {
/*intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(
DocumentsContract.buildRootUri(AUTHORITY_MEDIA, "videos_root"),
DocumentsContract.Root.MIME_TYPE_ITEM);
intent.addCategory(Intent.CATEGORY_DEFAULT);*/
Uri saveUri = FileProvider.getUriForFile(this, FILE_PROVIDER, mRecordFile);
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(saveUri, "video/mp4");
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, stop ? PendingIntent.FLAG_UPDATE_CURRENT : PendingIntent.FLAG_ONE_SHOT);
Notification notification = new Notification.Builder(this)
.setContentTitle(getString(stop ? R.string.touch_stop_screen_record : R.string.go_saved_path))
.setContentText(mFilePath)
.setSmallIcon(R.drawable.screen_record_notification)
.setAutoCancel(stop ? false : true)
.setContentIntent(contentIntent)
.setChannelId(channelID)
.build();
notificationManager.notify(NOTIFICATION_ID, notification);
}
private void cancelNotification() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
notificationManager.cancel(NOTIFICATION_ID);
}
安卓O和之前的不一样的地方是,O之后通知必须创建NotificationChannel,创建后在notification中设置对应的channelID即可,创建的方法
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelID = getPackageName() + NOTIFICATION_ID;
NotificationChannel channel = new NotificationChannel(channelID, "screen_recorder", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
接下来是通知的自动取消,因为有个需求是,开始录屏时发送一个通知告诉用户开始了,稍后就自动消失,但是在结束录屏的时候,需要常驻在通知栏中
.setAutoCancel(stop ? false : true) 用到的就是这个,true就是可自动取消
通知的点击事件呢?就是给通知设置一个PendingIntent,然后在setContentIntent中设置,由于,通知是要点击之后跳转到相应的页面,通知消失,所以这里设置的是FLAG_ONE_SHOT
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); .setContentIntent(contentIntent)
通知的更新呢? 就是将flag修改成update即可
stop ? PendingIntent.FLAG_UPDATE_CURRENT : PendingIntent.FLAG_ONE_SHOT
通知的取消就是cancel了,传入需要取消的通知id即可
notificationManager.cancel(NOTIFICATION_ID);