我有一个开关可以打开和关闭服务。 问题是它不能关闭服务,我不知道为什么, 该服务实现了SensorEventListener,其想法是应用程序将检测手机的移动而不在应用程序内。
但是关闭开关不起作用。 有什么想法为什么服务不会停止?
服务:
public class MyService extends Service implements SensorEventListener {
private Sensor accelerometer;
private SensorManager sm;
private Float MinFallValue,MaxFallValue;
public FallDetectorService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
return START_STICKY;
}
@Override
public void onDestroy(){
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.values[2] < MinFallValue)){
// Do something
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
MainActivity:
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Toast.makeText(SettingActivity.this, "Starting service", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SettingActivity.this, MyService.class);
startService(intent);
}
else{
Toast.makeText(SettingActivity.this,"Stoping service",Toast.LENGTH_LONG).show();
Intent intent = new Intent(SettingActivity.this, MyService.class);
stopService(intent);
}
}
});