thread, or UI thread. The runtime environment manages the UI thread, so you don’t have to. Long-running operations of any length can block the UI thread, and some kinds of operations are just not allowed. If you’re not drawing pixels or handling user interaction, your code may block those two responsibilities. Android Threads
private memory area that is mainly used to store method local variables and parameters during the execution of [the thread]. The private memory area is allocated when the thread is created and deallocated once the thread terminates." There is a small delay each time execution jumps from one thread to another.
InternalHandler extends Handler {! @Override! public void handleMessage(Message msg) {! AsyncTaskResult result = (AsyncTaskResult) msg.obj;! switch (msg.what) {! case MESSAGE_POST_RESULT:! // There is only one result! result.mTask.finish(result.mData[0]);! break;! case MESSAGE_POST_PROGRESS:! result.mTask.onProgressUpdate(result.mData);! break;! }! }! }
thread. 2. Task should be able to signal success and failure back to the UI thread. 3. Task module should run subtasks in sequence. 4. Asynchronous subtasks should trigger the next task step when they are finished. 5. Task code should be easy for developers to understand.
Fetch user account with a network request 3. Create a new local DB 4. Sync (push) remote DB with new local DB 5. Cancel login if syncing the remote DB fails 6. Catch exceptions 7. Remove old scheduled alarms 8. Copy a few settings from old to new DB 9. Stop replication on the old database 10. Delete the old database 11. Set the new database as the active one 12. Sync (push) the new database 13. Show a success response to the user (but only when syncing is done!) Building a login task
Fetch user account with a network request 3. Create a new local DB 4. Sync (push) remote DB with new local DB 5. Cancel login if syncing the remote DB fails 6. Catch exceptions 7. Remove old scheduled alarms 8. Copy a few settings from old to new DB 9. Stop replication on the old database 10. Delete the old database 11. Set the new database as the active one 12. Sync (push) the new database 13. Show a success response to the user (but only when syncing is done!)
public interface MyCallback() {! public void onSuccess();! public void onFailure();! }! ! // rest of task implementation! public void start(MyCallback callback) {! // call onSuccess or! // onFailure here!! } public void onSuccess() {! rr.send(RESULT_OK);! }! ! public void onFailure() {! rr.send(RESULT_CANCEL);! }! ! myTaskModule.start(this); Pass the Service into the task module as a callback implementation. start
Defines the ResultReceiver Starts a background thread Defines task components Runs task components Starts the Service Starts the task module Starts executing task Shows task outcome in UI Binds itself to the task module Communicates to the Service Communicates to the Activity Defines service communication Stops the thread