Android8.0启动Service

Android8.0出来后,为了提高设备的性能,对于service也做了相应的改变。

  • 如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 [startService()] 函数,则该函数将引发一个 [IllegalStateException]
  • 新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 [startForeground()] 函数。

详细android8.0变更请参考https://developer.android.google.cn/about/versions/oreo/android-8.0-changes

代码实现

在原来 startService的代码处修正

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//启动前台服务
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
         }

在service类中onCreate()方法中新建一个Notification ,记住Android8.0后对于Notification新增了一个渠道channel;
最后加上startForeground(1, notification);

public void onCreate() {
        super.onCreate();
//新建Notification
        NotificationChannel channel = new NotificationChannel("1", "channel_name",
                NotificationManager.IMPORTANCE_HIGH);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
        Notification notification = new Notification.Builder(getApplicationContext(), "1").build();

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