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

时间:2016-10-14 07:21:00

标签: android broadcastreceiver android-service android-location

您好我正在构建一个应用程序,我正在使用位置服务。该服务必须一直工作,所以我设置当服务转到onDestroy时,然后意图被发送到再次启动服务的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));
    }

如何防止用户点击退出按钮时,我的服务不会再次创建?提前谢谢。

1 个答案:

答案 0 :(得分:2)

只有在单击注销按钮时才能使用shouldRestart的静态布尔变量false,否则true

添加到您的活动:

public static boolean shouldRestart=true;

添加到您的"退出按钮点击事件"这一行:

shouldRestart=false;

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

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