废话不多说,下面是简单使用,如果是Android8.0以下,中间的兼容可忽略。
发送通知:
博主写的这个Demo是两个按钮,一个负责发送通知,一个取消通知
取消通知:
Demo代码如下
public class NotificationDemo extends AppCompatActivity implements View.OnClickListener {private Button btn_nts;private Button btn_ntv;@Overrideprotected 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);}@Overridepublic 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);}
}