我无法让一个衍生的线程停止:
我正在常规的Android Phone.apk中实现Ringer级的振动部分(基本上是逐字逐句),但是在正确振动一次(并停止)之后,我第二次调用startVibration()
并且随后stopVibration()
,它不停止线程(日志打印出mVibratorThread为空,即使它的一个实例显然仍处于活动状态,因为手机在振动: - )!)...
public volatile boolean mContinueVibrating;
public VibratorThread mVibratorThread;
private static final int VIBRATE_LENGTH = 1000; // ms
private static final int PAUSE_LENGTH = 1000; // ms
public void startVibration(){
//Start the vibration alarm
if (mVibratorThread == null) {
mContinueVibrating = true;
mVibratorThread = new VibratorThread();
Log.i(TAG, "Starting vibration...");
mVibratorThread.start();
}
}
public void stopVibration(){
//Stop the vibration alarm
Log.i(TAG, "Stopping vibration...");
if (mVibratorThread != null){
mContinueVibrating = false;
mVibratorThread = null;
Log.i(TAG, "Thread wasn't null, but is now set to null...");
} else {
Log.i(TAG, "Thread was null...");
}
}
private class VibratorThread extends Thread {
public void run() {
Vibrator mVibrator = (Vibrator) m_context.getSystemService(Context.VIBRATOR_SERVICE);
while (mContinueVibrating) {
mVibrator.vibrate(VIBRATE_LENGTH);
SystemClock.sleep(VIBRATE_LENGTH + PAUSE_LENGTH);
Log.i(TAG, "VIBRATING NOW!!" + mContinueVibrating);
}
}
}
我已经尝试了Where to stop/destroy threads in Android Service class?
中描述的方法感谢您的帮助,
尼克
答案 0 :(得分:1)
请从Handler
调用startVibrator和stopVibrator这是Handler http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html
的教程答案 1 :(得分:0)
问题在于引用Thread的类在进程的中途被重新启动,并且该类的新实例自然不知道其前任发起的线程,因此引用了线程为空。我通过将线程放在它自己的单例类中来修复它。