背景
在android 10及以上版本,后台服务不允许定时在通知栏发送信息,其中有两种解决方案:
1.将对话框设置后台常驻方式(startForeground)
这种方式有个不好的地方在于,每次应用一打开,该通知栏也会自动打开。其使用方法不再做详细讲解,我这里主要讲解第二种使用方式JobIntentService。
2.JobIntentService
首先创建一个InitIntentService 继承于JobIntentService
public class InitIntentService extends JobIntentService {
Notification notification=null;
private final int NotificationID = 0x10000;
public static final int JOB_ID = 1;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, InitIntentService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
// 具体逻辑
}
}
private void proNotification(String cotent) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
androidx.core.app.NotificationCompat.Builder builder = null;
String channelId = "com.message.notify";
String channelName = "notification";
//判断api版本大于等于26
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel =new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
manager.createNotificationChannel(channel);
builder = new androidx.core.app.NotificationCompat.Builder(this, channelId);
}else {
builder = new androidx.core.app.NotificationCompat.Builder(this);
builder.setChannelId(channelId);
}
builder
.setContentText(cotent)
.setWhen(System.currentTimeMillis())//设置消息通知发送时间
.setSmallIcon(R.mipmap.ic_launcher)//设置小童通知状态栏图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//设置消息通知下拉图标
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_MAX);//设置消息优先级
//设置消息通知点击意图
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
//点击消息通知后删除的两种实现方法
//第一种
builder.setAutoCancel(true);
//第二种
// int notificationId = 1;
// manager.cancel(notificationId);
//设置消息通知的提醒效果
builder.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luan.ogg")))//设置消息声音
.setVibrate(new long[]{0, 1000, 1000, 1000})//设置消息震动,需要加入android.permission.VIBRATE权限
.setLights(Color.GREEN, 1000, 1000)//设置消息提醒灯
.setDefaults(androidx.core.app.NotificationCompat.DEFAULT_ALL);//设置默认效果
//设置悬挂弹出
builder.setVisibility(androidx.core.app.NotificationCompat.VISIBILITY_PUBLIC);
builder.setFullScreenIntent(pendingIntent, true);
notification = builder.build();
// startForeground(NotificationID, notification);
manager.notify(NotificationID, notification);
}
end:
以上就是解决Notification报错的最新解决方式。 注:本篇文章只用于记录问题,如有帮助请记得点赞哦!!!!