android 8.0以后 不再支持后台运行服务了,

所以如果想暂时的适配之前的工程

可以修改targetSdkVersion到26以下版本

targetSdkVersion 25

如果想正儿八经的适配

可以通过启动前台服务来启动

前台服务依然不能依然不能做后台的事情

public static void startMyService(Context content, Intent intent) {
// content.startService(intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android8.0以上通过startForegroundService启动service
content.startForegroundService(intent);
} else {
content.startService(intent);
}
}

而且服务启动5s内 必须得调用

startForeground

方法

我这边来一个简单的封装

@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(int i) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "my_channel_01";
// 用户可以看到的通知渠道的名字.
CharSequence name = getString(R.string.app_name);
// 用户可以看到的通知渠道的描述
String description = getString(R.string.app_desc);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(id, name, importance);
}
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// 最后在notificationmanager中创建该通知渠道 //
mNotificationManager.createNotificationChannel(mChannel);

// 为该通知设置一个id
int notifyID = 1;
// 通知渠道的id
String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel.
String content = "前台通知内容";
Notification notification = new Notification.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name)).setContentText(content)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setChannelId(CHANNEL_ID)
.build();
startForeground(1, notification);
}

可以在service中的

onStartCommand

中调用

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(i);
}

后台服务的替代品暂时还没找到。有人说可以使用

public class TestJobService extends JobService

但是又有人说这个JobService服务只能后台运行10分钟 那根本就不够用的