Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何销毁/终止服务?_Java_Android_Android Service - Fatal编程技术网

Java 如何销毁/终止服务?

Java 如何销毁/终止服务?,java,android,android-service,Java,Android,Android Service,我让我的应用程序运行一个检测震动的服务,但是在我的MainActivity中,我有一个用于注销用户的按钮,在该按钮中,我必须注销并终止检测震动事件的服务 我在我的MainActivity中注销的方法是: public void signOutAndFinish(){ //Stop Shakeservice Intent intent = new Intent(this, ShakeService.class); stopService(intent); //Go

我让我的应用程序运行一个检测震动的服务,但是在我的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();
}
如何终止服务,以便在我注销时服务终止


谢谢你的帮助

您可以在服务的
ondestory()
方法中将广播发送回您的活动,然后注销

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

这是为您服务的:

@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...
    }
}
但是,如果我在注销后抖动设备,服务会识别抖动

然后,您可能没有清理服务的
onDestroy()
方法中的
传感器

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

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