Pages

August 29, 2010

Android UI Thread & Massive Work Thread

Many times Android Application becomes in-responsive due to heavy load on UI thread & user gets "FORCE CLOSE" message.

Avoid performing long-running operations (such as network I/O) directly in the UI thread — the main thread of an application where the UI is run — or your application may be blocked and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:

There is simple solution to make application that does Massive work & need to frequently update UI.
Solution is to create a mechanism using  android.os.handler ,
  1. Create a Handler object in your UI thread
  2. Spawn off worker threads to perform any required expensive operations
  3. Post results from a worker thread back to the UI thread via Message Object.
  4. Update the views on the UI thread as needed
Below is simple solution:

public class MyActivity extends Activity {

    [ . . . ]
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        [ . . . ]
    }

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do 

        // directly in the UI thread 

        Thread t = new Thread() {
            public void run() {
                mResults = doSomethingExpensive();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on 

        //the data in mResults
        [ . . . ]
    }
}
Article on Android.com | Common Task

No comments:

Post a Comment