开发者

Reference to running Thread is null

I can't get a spawned thread to stop:

I'm implementing the vibration-part of the Ringer-class in the regular Android Phone.apk (basically word for word), but after vibrating once (and stopping) correctly, the second time I call startVibration() and subsequently stopVibration(), it doesn't stop the thread (the log prints out that mVibratorThread is null, even though an instance of it is clearly still active, because the phone is vibrating :-)!)...

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);
开发者_如何学JAVA            SystemClock.sleep(VIBRATE_LENGTH + PAUSE_LENGTH);
            Log.i(TAG, "VIBRATING NOW!!" + mContinueVibrating);
        }
    }
}

I've already tried the method described in Where to stop/destroy threads in Android Service class?

Thanks for your help,

Nick


Please call the startVibrator and stopVibrator from a Handler

here is the tutorial for Handler http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html


The issue was that the class that was referencing the Thread was being re-initiated halfway through the process, and the new instance of the class naturally had no knowledge of the thread that was initiated by its predecessor, so the reference to the thread was null. I fixed it by putting the thread in its own, singleton class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜