点击按钮实现弹窗通知
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_notice:
//创建点击后跳转页面intent
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
//创建channel
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("001", "my_channel", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点
channel.setLightColor(Color.GREEN); //小红点颜色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
manager.createNotificationChannel(channel);
}
//创建通知
Notification notification = new NotificationCompat.Builder(this, "001")
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.setAutoCancel(true)
.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/luna.ogg")))
.setVibrate(new long[]{0, 1000, 1000, 1000})//震动
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
checkNotifySetting();
manager.notify(1, notification);
break;
default:
break;
}
}
private void checkNotifySetting() {
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
// areNotificationsEnabled方法的有效性官方只最低支持到API 19,低于19的仍可调用此方法不过只会返回true,即默认为用户已经开启了通知。
boolean isOpened = manager.areNotificationsEnabled();
if (isOpened) {
Toast.makeText(this, "通知权限已经被打开", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "通知权限未开启", Toast.LENGTH_SHORT).show();
openPermission();
}
}
private void openPermission(){
try {
// 根据isOpened结果,判断是否需要提醒用户跳转AppInfo页面,去打开App通知权限
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
//这种方案适用于 API 26, 即8.0(含8.0)以上可以用
intent.putExtra(EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(EXTRA_CHANNEL_ID, getApplicationInfo().uid);
//这种方案适用于 API21——25,即 5.0——7.1 之间的版本可以使用
//intent.putExtra("app_package", getPackageName());
//intent.putExtra("app_uid", getApplicationInfo().uid);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}