如何从注销按钮停止服务?

How to stop service from logout button?

您好,我正在构建一个应用程序,我在其中使用位置服务。该服务必须一直工作,所以我将其设置为当服务进入 onDestroy 时,然后将 intent 发送到再次启动服务的 BroadcastReceiver,这样,我的服务将始终工作。但是我想在用户单击按钮注销时停止服务。如何防止这种情况,当服务进入 onDestroy 时,不发送广播意图(但仅当用户单击注销时)? 这是我从 MainActivity 注销:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_log_out) {
            if (isNetworkConnected()) {
                unsubscribingFromFirebase();
                removeTokenAndAccountFromSharedPreferences();

                stopService(mServiceIntent);
                Log.i("MAIN_ACTIVITY", "Logout!");

                Log.d("MAIN_ACTIVITY " , "Internet access ");
            }
            else {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
            }
        }

这些是位置服务中的 onStartCommand、onCreate 和 onDestroy 方法:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("onStartCommand" , "LocationService");
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isEnded = false;
        mRequestingLocationUpdates = false;
        mLastUpdateTime = "";
        Bugsnag.init(this, BUGSNAG_API_KEY);

        buildGoogleApiClient();
        Log.d("onCreateService", "onCreateService");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "onDestroy!");
        timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
        SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.user_location), MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("onDestroyService", timeWhenServiceDestroyed);
        editor.apply();
        stopLocationUpdates();
        Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
        Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
    }

这是我的 BroadCastReceiver:

@Override
    public void onReceive(Context context, Intent intent) {
        Log.i(LocationServiceRestartBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, LocationService.class));
    }

如何防止当用户点击注销按钮时,我的服务不再创建?提前致谢。

您可以使用静态布尔变量 shouldRestartfalse 仅当单击注销按钮时,否则 true.

添加到您的 activity :

public static boolean shouldRestart=true;

添加到您的"logout button click event"这一行:

shouldRestart=false;

并在 onDestroy 服务方法中添加此行:

if (MainActivity.shouldRestart){
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
    sendBroadcast(broadcastIntent);
}
MainActivity.shouldRestart=true;