Friday, May 11, 2012

[android-developers] Re: Thread lifetime

OK, I got it working, and here is how I did it. I defined an extension
of Thread:

public class AudioInputThread extends Thread{
private boolean requestWorking = false;
private boolean isWorking = false;

public void run()
{
while(true)
{
try
{
if(isWorking)
{
//..read and analyze a block of audio..
//..when we want to post to the main activity, we do this:
synchronized(Main.audioThreadSync){
if(Main.activeInstance != null)

Main.handler.post(Main.activeInstance.doUpdatePhaseDisplay);
}
if(!requestWorking)
isWorking = false;
}
else //..isWorking is currently false
{
if(requestWorking)
isWorking = true;
else
Thread.sleep(2000);
}
} //..end of try block
catch (InterruptedException ex) { /* just loop back and do more
work */ }
} //..end of while(true) block
} //..end of the run() method for this thread

public void startWorking()
{
if(! isWorking )
{
requestWorking = true;
this.interrupt();
while( ! isWorking ) //..wait for the request to be
acknowledged
Thread.yield();
}
}

public void stopWorking()
{
if(isWorking)
{
requestWorking = false;
this.interrupt();
while( isWorking )
Thread.yield();
}
}

} //..end of this class definition

So the thread is always running, but it does nothing if isWorking is
false. The interrupt is to force an early termination from the
sleep(2000). The object audioThreadSync is just a static
syncrhonization object in Main (the main activity) to protect accesses
to activeInstance. The main activity sets activeInstance to "this" in
onResume() and sets it to null in onPause(). If activeInstance is
null then this audio thread can continue to read and analyze data
using all static variables. It just can't post any results to the
main activity because the main activity might not exist. The use of
requestWorking and isWorking ensures that the thread will only change
isWorking at safe times. Obviously the main activity must call
stopWorking() before shutting down the AudioRecord object.

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate