我正试图停止我的服务,但我不能,我不知道为什么。 还有一个问题:我怎样才能运行一次服务类?表示一个类服务,如果第二次运行不重启或重新启动。 感谢您的关注- 我的代码:
我用:
intent = new Intent(G.context, MyService.class);
G.context.stopService(intent);
在myservice类中:
public class MyService extends Service {
MediaPlayer myMediaPlayer;
MediaPlayer myMediaPlayer2;
public ShakeDetector mShakeDetector;
public SensorManager mSensorManager;
public Sensor mAccelerometer;
public boolean shake = true;
Handler handler;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
handler = new Handler();
Log.e("LOG", "Service Start");
myMediaPlayer = MediaPlayer.create(MyService.this,
R.raw.play3);
myMediaPlayer2 = MediaPlayer.create(MyService.this,
R.raw.play1);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new ShakeDetector.OnShakeListener() {
@Override
public void onShake() {
myMediaPlayer.start();
}
});
}
@Override
public void onStart(Intent intent, int startId) {
}
@Override
public void onDestroy() {
super.onDestroy();
myMediaPlayer.pause();
myMediaPlayer2.pause();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI, new Handler());
return START_STICKY;
}
}