解決Android O 錯誤Context.startForegroundService() did not then call Service.startForeground

原因分析
Android 8.0 有以下調整:
Android 8.0 的應用嘗試在不允許其創建後臺服務的情況下使用 startService() 函數,則該函數將引發一個 IllegalStateException。

新的 Context.startForegroundService() 函數將啓動一個前臺服務。現在,即使應用在後臺運行,系統也允許其調用 Context.startForegroundService()。
應用必須在創建服務後的五秒內調用該服務的 startForeground() 函數。
app代碼:

Intent intent = new Intent(this, TestService.class);
intent.putExtra("type",1);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     startForegroundService(intent);
 } else {
     startService(intent);
 }

TestService代碼

   private NotificationManager notificationManager;
    private static final String NOTIFICATION_ID = "channedId";
    private static final String NOTIFICATION_NAME = "channedId";
    @Override
    public void onCreate() {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //創建NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,getNotification());       
    }
      @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("測試服務")
                .setContentText("我正在運行");
        //設置Notification的ChannelID,否則不能正常顯示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(NOTIFICATION_ID);
        }
        Notification notification = builder.build();
        return notification;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章