先說遇到的問題,就是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
源碼如下:已測試通過,可以運行
https://download.csdn.net/download/u013075460/12367214