Android 开启Service报错 兼容


        startForeground(1, new Notification());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("1", "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            mNotificationManager.createNotificationChannel(channel);
        }
   @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLockScreenReceiver);
        unregisterReceiver(phoneReceiver);
        stopForeground(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && mNotificationManager != null) {
            mNotificationManager.cancelAll();
        }

    }

 

调用的时候

intent = new Intent(this, MusicService.class);
        intent.setAction(MusicService.ACTION_Play);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }

 

你可能感兴趣的:(Android 开启Service报错 兼容)