Tuesday, August 26, 2014

Threading

All Android application components — including
Activities
Services
Broadcast Receivers
— start on the main application thread

Android offers two alternatives for backgrounding your processing.
  • AsyncTask
  • custom implementation of Threads
Using AsyncTask to Run Asynchronous Tasks

Offers the convenience of event handlers synchronized with the GUI thread to let you update Views and other UI elements to report progress or publish results when your task is complete



Creating a new Asynchronous Task

AsyncTask<[Input Parameter Type], [Progress Report Type], [Result Type]>

private class MyAsyncTask extends AsyncTask<String, Integer, Integer> {
  @Override
  protected void onProgressUpdate(Integer... progress) {
    // [... Update progress bar, Notification, or other UI element ...]
  }

  @Override
  protected void onPostExecute(Integer... result) {
    // [... Report results via UI update, Dialog, or notification ...]
  }

  @Override
  protected Integer doInBackground(String... parameter) {
    int myProgress = 0;
    // [... Perform background processing task, update myProgress ...]
    PublishProgress(myProgress)
    // [... Continue performing background processing task ...]

    // Return the value to be passed to onPostExecute
    return result;
  }
}

doInBackground
  • This method will be executed on the background thread
  • Use the publishProgress method to allow onProgressUpdate to post progress updates to the UI
  • When your background task is complete, return the final result for the onPostExecute handler to report it to the UI.
onProgressUpdate
  • Override this handler to post interim updates to the UI thread.
  • This handler is synchronized with the GUI thread when executed, so you can safely modify UI elements.
onPostExecute
  • When doInBackground has completed, the return value from that method is passed in to this event handler.
  • Use this handler to update the UI once your asynchronous task has completed
Running an Asynchronous Task

new MyAsyncTask().execute("inputString1", "inputString2");



Manual Thread Creation and GUI Thread Synchronization

Creating a new Thread

// This method is called on the main GUI thread.
private void mainProcessing() {
  // This moves the time consuming operation to a child thread.
  Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background");
  thread.start();
}

// Runnable that executes the background processing method.
private Runnable doBackgroundThreadProcessing = new Runnable() {
  public void run() {
    backgroundThreadProcessing();
  }
};

// Method which does some processing in the background.
private void backgroundThreadProcessing() {
  [ ... Time consuming operations ... ]
}

If you are running within an Activity, you can also use the runOnUiThread method, which lets you force a method to execute on the same thread as the Activity UI.

Synchronizing with the Activity’s GUI thread

runOnUiThread(new Runnable() {
    public void run() {
        // TODO Update a View.
    }
});

In other circumstances (such as Toasts and Notifications) you can use the Handler class to post methods onto the thread in which the Handler was created

// *******************************************************************
// ** Using a Handler to synchronize with the GUI thread
// Initialize a handler on the main thread.
private Handler handler = new Handler();

private void mainProcessing() {
  Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background"); 
  thread.start();
}

private Runnable doBackgroundThreadProcessing = new Runnable() {
  public void run() {
    backgroundThreadProcessing();
  }
};

// Method which does some processing in the background.
private void backgroundThreadProcessing() {
  [ ... Time consuming operations ... ]
  handler.post(doUpdateGUI); 
}

// Runnable that executes the update GUI method.
private Runnable doUpdateGUI = new Runnable() {
  public void run() {
    updateGUI();
  }
};

private void updateGUI() {
  [ ... Open a dialog or modify a GUI element ... ]
}

Examples

Hangs UI

public void startCounter(View view) {
    for (int i=0; i<=1000; i++) {
          txtView1.setText(String.valueOf(i));
          try {
                   Thread.sleep(1000);
                } catch (InterruptedException e) {}
          }
    }

This ties up the UI, which is waiting for the display of the numbers to be completed.

A Thread trying to access a View on the UI

  public void startCounter(View view) {  
    Log.d("Threading", "running");
    new Thread(new Runnable() {
@Override
public void run() {
    for (int i=0; i<=1000; i++) {
    Log.d("Threading", "running");
    txtView1.setText(String.valueOf(i));
    try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("Threading", e.getLocalizedMessage());
}
    }    
}    
    }).start();

This code that is placed inside the Runnable block is on a separate thread, which tries to update the UI, which is not a safe thing to do because Android UIs are not thread-safe.

Using Post method on a View inside a Thread

To resolve this, you need to use the post() method of a View to create another Runnable block to be added to the message queue. 

The new Runnable block created will be executed in the UI thread

    public void startCounter(View view) 
    {  
    //Do not hangup the UI
    new Thread(new Runnable() {
    @Override
    public void run()
    {
    for(int i = 0; i <= 1000; i++)
    {
    final int valueOfI = i;
   
    //Place the job of updating the UI in the message queue
    txtView1.post(new Runnable() {
    public void run()
    {
    txtView1.setText(String.valueOf(valueOfI));
    }
    });
   
    try
    {
    Thread.sleep(1000);
    }catch(InterruptedException e)
    {
    Log.d("Threading ", e.getLocalizedMessage());
    }
    }
    }
    }
    ).start();        
    }    
Using a Handler to update UI

static Handler UIupdater = new Handler() {
@Override
public void handleMessage(Message msg) {              
byte[] buffer = (byte[]) msg.obj;

//---convert the entire byte array to string---
String strReceived = new String(buffer);

//---display the text received on the TextView---              
txtView1.setText(strReceived);
Log.d("Threading", "running");
}
};
    
    public void startCounter(View view) {  
    new Thread(new Runnable() {
    @Override
    public void run() {    
    for (int i=0; i<=1000; i++) {    
    //---update the main activity UI using a UIupdater
                    ThreadingActivity.UIupdater.obtainMessage(
                        0,  String.valueOf(i).getBytes() ).sendToTarget();
   
    //---insert a delay    
    try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("Threading", e.getLocalizedMessage());
}
    }
    }    
    }).start();
    }

https://github.com/coderetriever/Android/tree/master/ThreadingTwo

https://github.com/coderetriever/Android/tree/master/ThreadingThree

https://github.com/coderetriever/Android/tree/master/ThreadFour

No comments:

Post a Comment