一,取消大部分静态注册广播
今天,我 在做下载任务的时候,通过广播监听下载进度,在7.0的时候正常,但运行在8.0上面,就失效了,查了一下,发现8.0开始取消了大部分的广播静态注册.
1,在需要监听的页面进行动态注册
IntentFilter filter = new IntentFilter();
filter.addAction(GUANGBO);
mUpdateAppReceiver = new UpdateAppReceiver();
registerReceiver(mUpdateAppReceiver, filter);
2,在页面销毁的时候(onDestory())记得取消监听
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUpdateAppReceiver);
}
3,发送广播,action必须和注册时的action一致
private static void sendProgress(Context context, int progress, String downloadMsg) {
Intent intent = new Intent();
intent.putExtra("progress", progress);
intent.putExtra("downloadMsg", downloadMsg);
intent.setAction(GUANGBO);
context.sendBroadcast(intent);
}
二,Notification和8.0使用方式和之前略有小区别,必须分开判断设置
String id = "channel_01";
String name = "渠道名字";
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//安卓8.0的设置
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
nm.createNotificationChannel(mChannel);
notification = new Notification.Builder(this)
.setChannelId(id)
.setContentTitle("正在下载 " + versionName)
.setProgress(100, progress, false)
.setSmallIcon(R.mipmap.ic_launcher).build();
} else {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("正在下载 " + versionName)
.setProgress(100, progress, false)
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true) // 将Ongoing设为true 那么notification将不能滑动删除
.setChannel(id);//无效
// .builder.setAutoCancel(true); // 将AutoCancel设为true后,当你点击通知栏的notification后,它会自动被取消消失
notification = notificationBuilder.build();
}
nm.notify(notifyId, notification);
//取消通知
private void cancelNotificaion() {
if (nm != null) nm.cancel(notifyId);
}