Android 8.0以上啓動Service

問題

在android 8.0以上版本谷歌對後臺service進行了嚴格限制,不允許後臺service默默的存在,若想用service,必須以startForegroundService的方式啓動service且必須在service內部5s內執行startForeground方法顯示一個前臺通知,否則會產生ANR或者crash。

解決問題

在MainActivity中啓動服務

Intent intent1 = new Intent();
intent1.setClass(this, TestService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent1);
} else {
    startService(intent1);
}

TestService類

public class TestService extends Service {

    private static final String ID = "channel_1";
    private static final String NAME = "前臺服務";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("日常打log", "onCreate");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(ID, NAME, NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(this, ID)
                    .build();
            startForeground(1, notification);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("日常打log", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        Log.d("日常打log", "onDestroy");
    }
}

注意 startForeground(1, notification);中不能爲0,不然會出現如下問題
Context.startForegroundService() did not then call Service.startForeground()




然後出現了***正在運行,使此服務在前臺運行,提供正在進行的服務在此狀態下向用戶顯示的通知。

ForegroundEnablingService
關閉前臺服務

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