Android 9.0版本及以上开发时遇到的一些版本问题
1.使用前台服务
要加上权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
同时通知部分的代码也要修改
//android 8.0以后新增
String CHANNEL_ONE_ID="com.example.servicetest";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if(Build.VERSION.SDK_INT >= 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 intent = new Intent(this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
Notification notification = new Notification.Builder(this)
.setChannelId(CHANNEL_ONE_ID)//新增
.setContentTitle("This is content title")
.setContentText("This is content title")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pi)
.build();
notification.flags |= Notification.FLAG_NO_CLEAR;//新增
startForeground(1,notification);
}