开发者

Android - Issue stopping a thread

开发者 https://www.devze.com 2023-02-27 06:44 出处:网络
In my application I start a thread that runs a couple audio services by pushing a button, then attempt to stop it by pushing a stop button. The audio portion stops fine, but I see in the debugging win

In my application I start a thread that runs a couple audio services by pushing a button, then attempt to stop it by pushing a stop button. The audio portion stops fine, but I see in the debugging window that the thread is still running. Any help would be greatly appreciated

Here is the thread that is started, goTime is initialized to null as a global variable:

goTime = new Thread(new Runnable() { 

        public void run() { 

    rec.startRecording();
    player.play();
    while(isRecording && !Thread.currentThread().isInterrupted()) {
        if(goTime.isInterrupted()){
            return;
        }
        ix=0;
        while(ix<buf开发者_JAVA技巧Leng){
        short[] bufferor = buffers[ix++ % buffers.length];
        lastRead = ix;
        rec.read(bufferor, 0, 
                    bufferor.length);
        buffers[ix]=bufferor;
        inter.onMarkerReached(rec);
        }
    }
    if(goTime.isInterrupted()){
        return;
    }
        }});
    goTime.start();

And here is the method called when the stop button is pressed:

    public void stop(View view){
    isRecording=false;
    System.out.println("stop called");
    rec.stop();
    player.stop();
    player.flush();
    player.release();
    goTime.interrupt();
    //isRecording=true;
}


sometimes the values of objects between threads are cached by the JVM(or in this case Dalvik) try declaring your isRecording like so:

private volatile boolean isRecording;

The volatile keyword will ensure the values are not cached but always written directly

0

精彩评论

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