通過AlarmManager+Service+廣播實現定時任務。並解決8.0之後service無法啓動的問題

先說遇到的問題,就是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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章