先说遇到的问题,就是service无法启动
在receiver里面添加这样的判断
@Override
public void onReceive(Context context, Intent intent) {
Log.d("AlarmReceiver", "haha");
Intent i = new Intent(context, LongRunningService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//这是8.0以后的版本需要这样跳转
context.startForegroundService(i);
} else {
context.startService(i);
}
}service里面添加这样的代码
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//创建NotificationChannel
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}startForeground(1,getNotification());
之后就可以正常启动,别忘了注册广播和service
源码如下:已测试通过,可以运行
【小技巧|通过AlarmManager+Service+广播实现定时任务。并解决8.0之后service无法启动的问题】https://download.csdn.net/download/u013075460/12367214