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 ,
- Create a Handler object in your UI thread
- Spawn off worker threads to perform any required expensive operations
- Post results from a worker thread back to the UI thread via Message Object.
- Update the views on the UI thread as needed
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