当不满足某些条件时,从onStartCommand停止服务

时间:2019-07-17 10:10:08

标签: android android-service

我有一个监听位置变化的服务。我使用位置管理器实例并在onStartCommand中请求位置更新,但是它要求我添加权限检查-ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION。如果用户未授予我要停止该服务的权限,那么我从stopSelf()呼叫return START_NOT_STICKYonStartCommand()是处理这种情况的好习惯吗?

这里是onStartCommand()

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "onStartCommand: ");

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            Log.d(TAG, "onStartCommand: missing permissions");
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            stopSelf();
        }
        else {

            mLocationListener = new MyLocationListener();
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 5000, 10, mLocationListener);

            prepareNotificationAndStartService();

        }

        return START_NOT_STICKY;
    }

   private void prepareNotificationAndStartService(){

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("Address place holder")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setOnlyAlertOnce(true)
            .build();

    startForeground(1, notification);
}

0 个答案:

没有答案