0

I am relativity new to Android programming.

From my activity I fire off a a Asynctask that does this:

onPreExecute(): sets up the AudioRecord and gets it ready to record

doInBackground():

while (!isCancelled())    {
    try
    {     
        shortsRead = recorder.read(intputbuffer,0,size);
        if (shortsRead <= 0)  {
            Log.e("AudioRead", "Audioread failed buffersize tried:" + " Sizeread:" + shortsRead);

           recorder.stop();
           recorder.release();
           Thread.sleep(500); 
           int bufferSizeInBytes = 4096 * 2;
           recorder = new AudioRecord(AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes);
           recorder.startRecording();

        }
    }
    catch(Throwable x)
    { 
         Log.w("Audio", "Error reading voice audio", x);
    }

}
recorder.stop();
recorder.release();
Log.i("Audio", "Killed Audio Thread");

When I change config (switch orientation) it will run onDestroy (cancels the asynctask) and then onCreate in quick succession.

What I believe happens is the previous Asynctask is still running and not able to cancel in time and onCreate makes a new one. The new one can't get at the mic because it is already taken by my the previous asynctask.

Is there something I can do to do this cleanly?

I tried using android:configChanges="keyboardHidden|orientation" in the AndroidManifest.xml but from what I read the problem is still there... it is just masked on an orientation change.

Nikhil
  • 16,194
  • 20
  • 64
  • 81
Bryce
  • 3
  • 1

2 Answers2

0

When orientation is changed onCreate will be fired. So don't start any AsyncTask in onCreate if your app had orientation support.

Kavin Varnan
  • 1,989
  • 18
  • 23
0

How to handle an AsyncTask during Screen Rotation?. have a look at the comment by Romain Guy. Also have a look at this link. https://groups.google.com/forum/?fromgroups=#!topic/android-developers/4dW4-KMUKJI. This should help you.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • I am going down the path of onRetaingNonConfigurationInstance() and saving my asynctask and reloading it on onCreate. Thanks! – Bryce Nov 05 '12 at 22:26