【问题标题】:How to destroy/kill a service?如何销毁/杀死服务?
【发布时间】:2019-03-30 17:46:23
【问题描述】:

我有我的应用程序运行抖动检测服务,但是在我的 MainActivity 中,我有注销用户的按钮,我必须在其中注销并终止检测到抖动事件的服务。

我在 MainActivity 中注销的方法是:

public void signOutAndFinish(){
    //Stop Shakeservice
    Intent intent = new Intent(this, ShakeService.class);
    stopService(intent);
    //Go to login activity
    Intent iLoginView = new Intent(this, LoginActivity.class);
    startActivity(iLoginView);
}

但是,如果我在退出后摇晃我的设备,服务会识别摇晃,就好像它不会立即杀死它:

Intent intent = new Intent(this, ShakeService.class);
stopService(intent);

onDestroy方法中的代码是:

@Override
public void onDestroy() {
    super.onDestroy();
}

我怎样才能终止服务,以便在我注销时服务死掉?

感谢您的帮助!

【问题讨论】:

    标签: java android android-service


    【解决方案1】:

    您可以在服务的onDestroy() 方法中向您的活动发送广播,然后注销。

    以下是上述想法的一些示例代码:

    这是为您服务:

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent();
        intent.setAction("com.example.broadcast.MY_NOTIFICATION");
        intent.putExtra("data","Notice for logout!");
        sendBroadcast(intent);
    }
    

    这是为你的活动准备的:

    private BroadcastReceiver br = new MyBroadcastReceiver();
    
    @Override
    public void onCreate() {
      IntentFilter filter = new IntentFilter("com.example.broadcast.MY_NOTIFICATION");
      registerReceiver(br, filter);
    }
    
    @Override
    public void onDestroy() {
      unregisterReceiver(br);
    }
    
    // An inner class at your activity
    public class MyBroadcastReceiver extends BroadcastReceiver {
        private static final String TAG = "MyBroadcastReceiver";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            YourActivity.this.finish();
            // or do anything you require to finish the logout...
        }
    }
    

    【讨论】:

      【解决方案2】:

      但是,如果我在退出后摇晃我的设备,服务会识别出摇晃

      那么大概你没有在服务的onDestroy() 方法中清理你的Sensor 东西。

      如何终止服务,以便在我注销时服务终止?

      你现在正在这样做。但是,如果您在服务中设置了某些内容,例如侦听来自 SensorManager 的事件,则需要清理这些内容,通常在服务的 onDestroy() 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多