FANDOM



an inner class that extends AsyncTask, AudioSynthesisTask.
AsyncTask defines a method called doInBackground, which runs any code that is placed
inside it in a thread that is separate from the main thread of the activity. This allows the
activity and its UI to be responsive

private class AudioSynthesisTask extends AsyncTask<Void, Void, Void>
{

@Override
protected Void doInBackground(Void... params) {

  final int SAMPLE_RATE = 11025;
  int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
  AudioFormat.CHANNEL_CONFIGURATION_MONO,
  AudioFormat.ENCODING_PCM_16BIT);
  AudioTrack audioTrack = new AudioTrack(
  AudioManager.STREAM_MUSIC, SAMPLE_RATE,
  AudioFormat.CHANNEL_CONFIGURATION_MONO,
  AudioFormat.ENCODING_PCM_16BIT,
  minSize,
  AudioTrack.MODE_STREAM);
  audioTrack.play();

  short[] buffer = {
    8130,15752,22389,27625,31134,32695,32210,29711,25354,19410,12253,
    4329,-3865,-11818,-19032,-25055,-29511,-32121,-32722,-31276,-27874,
    -22728,-16160,-8582,-466 
  };

  while (keepGoing) {
    audioTrack.write(buffer, 0, buffer.length);
  }

return null;
}
}

ExamplesEdit

There is an example on how to use AsyncTask to avoid ANR warnings;

http://developer.android.com/training/articles/perf-anr.html


private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
    // Do the long-running work in here
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    // This is called each time you call publishProgress()
    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    // This is called when doInBackground() is finished
    protected void onPostExecute(Long result) {
        showNotification("Downloaded " + result + " bytes");
    }
}



new DownloadFilesTask().execute(url1, url2, url3);

ReferencesEdit

Hack 23 from 50 Android Hacks - syncAdapter Pattern