一、考虑系统差异,从8.0系统开始,Google引入通知渠道的概念。
@1:什么是通知渠道?
顾名思义,就是每条通知都要属于一个对应的渠道。每个App都可以自由地创建当前App拥有哪些通知渠道,但是这些通知渠道的控制权都是掌握在用户手上的。用户可以自由地选择这些通知渠道的重要程度,是否响铃、是否振动、或者是否要关闭这个渠道的通知。
@2:为什么要引入通知渠道?
因为引入渠道后,用户可以自主地选择自己关心哪些通知、不关心哪些通知。
@3:通知渠道引入后的影响。
二、开发步骤:
1、创建通知渠道。
@1:注意进行系统版本检查,注意创建通知渠道在8.0以下版本手机上会造成崩溃。
@2:关键代码:
/**
* 创建通知渠道
* 创建通知渠道的代码只会在首次执行时才会创建,之后执行时若发现
* 该通知渠道已存在,就不会再重复创建,因此不会影响效率。
* @param channelId
* @param channelName
* @param importance
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance){
NotificationChannel channel = new NotificationChannel(channelId,channelName,importance);
channel.setShowBadge(false); //设置不允许这个渠道下的通知显示角标
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
//调用创建渠道通知方法
String channelId = "chat"; //渠道ID
String channelName = "聊天消息"; //渠道名称
int importance = NotificationManager.IMPORTANCE_HIGH;//设置渠道重要程度
createNotificationChannel(channelId,channelName,importance);
2、发送消息通知
@1:通过构建方法,创建NotificationManager和Notification来发送消息通知。
@2:关键代码:
/**
* 发送聊天消息通知
* @param view
*/
public void sendChatMsg(View view){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent p1 = PendingIntent.getActivity(this,0,intent,0);
Notification notification = new NotificationCompat.Builder(this,"chat")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentTitle("收到一条新消息")
.setContentText("哈哈哈,今天我很开心。")
.setContentIntent(p1) //设置通知栏单击跳转
.build();
manager.notify(1,notification);
}
3、引导用户打开通知渠道。
//若用户将通知渠道关闭了,提供打开渠道的提示,以及跳转到相应界面。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = manager.getNotificationChannel("chat");
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE){
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE,getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID,channel.getId());
startActivity(intent);
Toast.makeText(this,"请手动将通知打开",Toast.LENGTH_SHORT).show();
}
}
4、删除通知渠道。(谨慎使用!)
/**
* 删除通知渠道
* @param view
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void deleteChatMsgChannel(View view){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.deleteNotificationChannel("chat"); //"chat"为通知渠道ID
}
在此推荐郭大神的解析:Android通知栏微技巧,8.0系统中通知栏的适配_guolin的博客-CSDN博客_importance_none