1.在我的MyBroadcastReceiver.java中:
Intent service = new Intent(context, TimerService.class);
// Android 8.0使用startForegroundService在前台启动新服务
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(service);
else
context.startService(service);
2.在我的TimeService.java中:
private static final String CHANNEL_ID = "11111";//渠道ID
private static final String CHANNEL_NAME = "TimerForegroundServiceChannel"; //渠道名称
//在android8.0以上版本,如果您的服务已启动(正在运行startService(Intent)),那么还应使该
//服务在前台运行,并在此状态下向用户提供持续显示的通知。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
IMPORTANCE);//构造NotificationChannel对象
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);//创建通知渠道
//在之前创建的渠道上发送一个通知(用CHANNEL_ID与之前创建的渠道关联)
Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID).build();
startForeground(1, notification);//将服务置于前台状态
}
这样就能正常使用服务了