第一行代码 10.5 前台服务
这里首先需要进行用户权限申请
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
增加后还是报错。
我的报错信息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.servicetest, PID: 5976
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread
MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
在报错中 Bad notification for startForeground 说明这个通知有问题,寻求原因后才知道:Android8.0时增加了对通知渠道这个东西,具体原因和解决方法可以参考 https://www.jianshu.com/p/8baa62c5bfc2.原理和实现都有提及。
附上代码:
String CHANNEL_ONE_ID = "CHANNEL_ONE_ID";
String CHANNEL_ONE_NAME= "CHANNEL_ONE_ID";
NotificationChannel notificationChannel= null;
//进行8.0的判断
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel= new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.jianshu.com/p/14ba95c6c3e2"));
PendingIntent pendingIntent= PendingIntent.getActivity(this, 0, intent, 0);
Notification notification= new Notification.Builder(this).setChannelId(CHANNEL_ONE_ID)
.setTicker("Nature")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("这是一个测试标题")
.setContentIntent(pendingIntent)
.setContentText("这是一个测试内容")
.build();
notification.flags|= Notification.FLAG_NO_CLEAR;
startForeground(1, notification);
-------------------------------在后面的最佳实现中,有点懵逼----------------------