废话不多说,下面是简单使用,如果是Android8.0以下,中间的兼容可忽略。
发送通知:
博主写的这个Demo是两个按钮,一个负责发送通知,一个取消通知
取消通知:
Demo代码如下
public class NotificationDemo extends AppCompatActivity implements View.OnClickListener {
private Button btn_nts;
private Button btn_ntv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_demo);
initView();
}
private void initView() {
btn_nts = (Button) findViewById(R.id.btn_nts);
btn_nts.setOnClickListener(this);
btn_ntv = (Button) findViewById(R.id.btn_ntv);
btn_ntv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_nts:
NotificationShow();
break;
case R.id.btn_ntv:
NotificationVanish();
break;
}
}
private void NotificationShow() {
//1.获取通知管理器类
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotificationDemo.this, "1");
/**
* 兼容Android版本8.0系统
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//第三个参数表示通知的重要程度,默认则只在通知栏闪烁一下
NotificationChannel channel = new NotificationChannel("NotificationID", "NotificationName", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); // 开启指示灯,如果设备有的话
channel.setLightColor(Color.RED); // 设置指示灯颜色
channel.setShowBadge(true); // 检测是否显示角标
// 注册通道
notificationManager.createNotificationChannel(channel);
builder.setChannelId("NotificationID");
}
//2.构建通知类
builder.setSmallIcon(R.mipmap.ic_launcher);//设置图标
builder.setContentTitle("微信");//标题
builder.setContentText("您有一条未读消息!");//内容
builder.setWhen(System.currentTimeMillis()); //时间
//builder.setDefaults(Notification.DEFAULT_ALL);
//SetDefaults 这个方法可选值如下:
// Notification.DEFAULT_VIBRATE :震动提示,Notification.DEFAULT_SOUND:提示音,Notification.DEFAULT_LIGHTS:三色灯,Notification.DEFAULT_ALL:以上三种全部
//3.获取通知
Notification notification = builder.build();
//4.发送通知
notificationManager.notify(1, notification);
}
private void NotificationVanish() {
//取消通知
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.cancel(1);
}
}