Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.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
Android stopService()未停止_Android_Android Service_Ondestroy - Fatal编程技术网

Android stopService()未停止

Android stopService()未停止,android,android-service,ondestroy,Android,Android Service,Ondestroy,这是我正在运行的代码,用于停止在后台运行的服务。如果我按下停止按钮,服务就会继续运行。onDestroy函数中的toast会运行,但服务不会停止。有什么帮助吗 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnStart = (Button) fi

这是我正在运行的代码,用于停止在后台运行的服务。如果我按下停止按钮,服务就会继续运行。onDestroy函数中的toast会运行,但服务不会停止。有什么帮助吗

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnStart = (Button) findViewById(R.id.btnStart);
    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), myServices.class));
            //dialContactPhone("123123123");
        }
    });
    Button btnstop = (Button) findViewById(R.id.btnStop);
    btnstop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), myServices.class));
        }
    });

}
这是服务中的代码

@Override
public int onStartCommand(Intent intent,  int flags, int startId) {
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
        // success! we have an accelerometer

        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        vibrateThreshold = accelerometer.getMaximumRange() / 2;
        running = false;
    } else {
        // fai! we dont have an accelerometer!
    }

    //initialize vibration

return START_STICKY;
}

@Override
public void onDestroy(){
    super.onDestroy();
    Toast.makeText(this, "Servive stoped", Toast.LENGTH_LONG).show();
}

如果“服务未停止”,您的意思是“传感器读数不断到达”,这是因为您没有在
onDestroy()
中注销侦听器。通过调用
onDestroy()
中的
SensorManager
上的
unregisterListener()
,传入您的侦听器(看起来像是
this
)。

如果说“服务没有停止”,您的意思是“传感器读数不断到达”,这是因为您没有在
onDestroy()中注销您的侦听器
。是的,这就是我的意思。我应该如何注销侦听器?