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()




然后出现了***正在运行,使此服务在前台运行,提供正在进行的服务在此状态下向用户显示的通知。
Android 8.0以上启动Service_第1张图片

ForegroundEnablingService
关闭前台服务

你可能感兴趣的:(Android)