设置前台服务 (将后台服务Service设置为前台服务 Service)
首先在manifest中添加权限:
接着第一步:在Service(自己编写的的继承于Sercive的类)中编写设置通知并开启前台服务的方法(函数),并调用,下面实例中设置通知方法是在onCreate()中调用的,下面实例前台化的服务类名为MediaService
private void setNotificationAndForeground() {
//判断当前版本是否支持
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "MediaSevice";
notificationChannel = new NotificationChannel(CHANNEL_ID, "主服务", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
//Channel.enableLights(true);//设置提示灯
//Channel.setLightColor(Color.RED);//设置提示灯颜色
//Channel.setShowBadge(true);//显示logo
//Channel.setDescription("MediaService notification");//设置描述
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
notification = new Notification.Builder(this, CHANNEL_ID)
.setAutoCancel(false)
.setContentTitle("音乐")//标题
.setContentText("开启中……")//内容
.setSmallIcon(R.drawable.playing_dark_style)//不设置小图标通知不会显示,或将报错
//.setLargeIcon(R.drawable.playing_dark_style)
.build();
startForeground(1, notification);//startForeground服务前台化,要在5秒内调用成功,否则前台化失败
}
}
在Service(自己编写的的继承于Sercive的类)中的onCreate()中调用setNotificationAndForeground()函数尝试设置通知并将Service设置为前台服务
@Override
public void onCreate() {
Log.e("onCreate", "onCreate\n======================================================\n");
super.onCreate();
setNotificationAndForeground();
//创建多媒体回调
//mediaControllerInterface_xj.setOnMediaProgressBack_xj(this);
}
第二步:在需要开启服务的地方开启前台服务
//判断当前版本是否支持前台服务,不支持则开启后台服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(getApplicationContext(), MediaService.class));
}else {
startService(new Intent(getApplicationContext(), MediaService.class));
}
}