一、问题表现
手机升级到Android 9.0测试的App的时候发现通知栏不显示了,之前Android 8.0显示还好好的,仔细研究了下,发现Android 8.0以后更新了API启用了以前创建通知栏方法。所以一般使用的时候还是最好使用新的API。
二、兼容方法
/**
* 开柜记录消息提醒
*
* @param context
* @param title
* @param msg
*/
public static void showOpenHistoryNotice(Context context, String title, String msg) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 创建
NotificationChannel channel = new NotificationChannel(String.valueOf(id), "通知", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(ContextCompat.getColor(context, R.color.c_ff6633));
channel.setShowBadge(true);
channel.setDescription("互救吧");
manager.createNotificationChannel(channel);
}
Intent clickIntent = new Intent(context, HomeMsgActivity.class);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, String.valueOf(id));
mBuilder.setContentTitle(title)
.setContentText(msg)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon))
.setOnlyAlertOnce(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.logo_white)
.setColor(ContextCompat.getColor(context, R.color.c_ff6633));
clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent clickPendingIntent = PendingIntent.getActivity(context, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// 点击删除
Intent cancelIntent = new Intent(context, NoticeCancelBroadcastReceiver.class);
cancelIntent.setAction("notice_cancel");
cancelIntent.putExtra("id", id);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_ONE_SHOT);
mBuilder.setContentIntent(clickPendingIntent);
mBuilder.setDeleteIntent(cancelPendingIntent);
mBuilder.setAutoCancel(true);
manager.notify(id, mBuilder.build());
}
Android 8.0以上添加NotificationChannel, id是通知栏id,在创建的时候最好直接使用,不然的话好像不会显示
PendingIntent 添加了点击和取消按钮
三、通知栏取消
通知栏取消只要注册一个静态广播就行了
/**
* @author Wudi
* @date 2018/9/17
*/
public class NoticeCancelBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String acton = intent.getAction();
if (acton.equals("notice_cancel")) {
int id = intent.getIntExtra("id", -1);
if (id != -1) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}
}
}
网友评论