Introduction to Android asynctask

Source: Internet
Author: User

Comparison between asynctask and handler

1) asynctask implementation principle, and applicable advantages and disadvantages

Asynctask is a lightweight asynchronous class provided by Android. It can inherit asynctask directly and implement asynchronous operations in the class,AndProvide interface feedback to the currentAsynchronous execution degree(Ui progress update can be implemented through the interface), and finally the execution result is fed back to the main UI thread.

Advantages:

L simple and fast

L process controllable

Disadvantages:

L it becomes complicated when multiple asynchronous operations and UI changes are required.

2) principle and advantages and disadvantages of handler asynchronous implementation

When handler is implemented asynchronously, it involves four objects: handler, logoff, message, and thread. the asynchronous process is that the main thread starts thread (subthread) à thread (subthread) run and generate message-à logoff to get the message and pass it to handler. the handler gets the message in logoff one by one and changes the UI.

Advantages:

L clear structure and clear Function Definition

L simple and clear for multiple background tasks

Disadvantages:

L when asynchronous processing is performed on a single backendCodeToo many, too complex structure (relative)

Introduction to asynctask Android asynctask is more lightweight than handler and is suitable for simple asynchronous processing. First, it is clear that android has handler and asynctask to avoid blocking the main thread (ui thread), and UI Updates can only be completed in the main thread, so asynchronous processing is inevitable.

Android provides asynctask to reduce the development difficulty. Asynctask is a encapsulated background task class. as its name implies, it is an asynchronous task.

Asynctask directly inherits from the object class and is located in Android. OS. asynctask. To use asynctask, we need to provide three generic parameters and reload several methods (at least one ).

 

Asynctask defines three generic types: Params, SS, and result.

    • Input parameters for Params startup task execution, such as the URL of the HTTP request.
    • Percentage of progress background tasks.
    • Result: The result returned when the task is executed in the background, such as string.

All the students who have used asynctask know that the following two methods are required to load data asynchronously:

    • Doinbackground (Params ...) The operations in the background can be put here. Note that you cannot directly operate the UI here. This method is executed in the background thread to complete the main work of the task, usually takes a long time. You can call publicprogress (progress…) during execution ...) To update the task progress.
    • Onpostexecute (result) is equivalent to handler's way of processing the UI, where you can use the result processing operation UI obtained in doinbackground. This method is executed in the main thread. The task execution result is returned as a parameter of this method.

If necessary, you have to rewrite the following three methods, but they are not required:

    • Onprogressupdate (progress ...) You can use the progress bar to increase user experience. This method is executed in the main thread to display the task execution progress.
    • Onpreexecute () is the interface used by the end user to call excute. This method is called before the task is executed. The progress dialog box is displayed here.
    • Oncancelled () the operation to be performed when the call is canceled

When using the asynctask class, the following guidelines must be followed:

    • Task instances must be created in the UI thread;
    • The execute method must be called in the UI thread;
    • Do not manually call the onpreexecute (), onpostexecute (result), doinbackground (Params...), onprogressupdate (Progress...) methods;
    • This task can only be executed once. Otherwise, exceptions may occur during multiple calls;

An example of a simple understanding of asynctask:

Main. xml

[Java] View plaincopy

  1. <? XML version ="1.0"Encoding ="UTF-8"?>
  2. <Linearlayout xmlns: Android =Http://schemas.android.com/apk/res/android"
  3. Android: Orientation ="Vertical"
  4. Android: layout_width ="Fill_parent"
  5. Android: layout_height ="Fill_parent"
  6. >
  7. <Textview
  8. Android: Id ="@ + ID/textview01"
  9. Android: layout_width ="Fill_parent"
  10. Android: layout_height ="Wrap_content"
  11. />
  12. <Progressbar
  13. Android: Id ="@ + ID/progressbar02"
  14. Android: layout_width ="Fill_parent"
  15. Android: layout_height ="Wrap_content"
  16. Style ="? Android: ATTR/progressbarstylehorizontal"
  17. />
  18. <Button
  19. Android: Id ="@ + ID/button03"
  20. Android: layout_width ="Fill_parent"
  21. Android: layout_height ="Wrap_content"
  22. Android: text ="Update progressbar"
  23. />
  24. </Linearlayout>

Mainactivity. Java

[HTML] View plaincopy

  1. Package Vic. Wong. Main;
  2. Import Android. App. activity;
  3. Import Android. OS. Bundle;
  4. Import Android. View. view;
  5. Import Android. View. View. onclicklistener;
  6. Import Android. widget. Button;
  7. Import Android. widget. progressbar;
  8. Import Android. widget. textview;
  9. Public class mainactivity extends activity {
  10. Private button;
  11. Private progressbar;
  12. Private textview;
  13. @ Override
  14. Public void oncreate (bundle savedinstancestate ){
  15. Super. oncreate (savedinstancestate );
  16. Setcontentview (R. layout. Main );
  17. Button= (Button) findviewbyid (R. Id. button03 );
  18. Progressbar= (Progressbar) findviewbyid (R. Id. progressbar02 );
  19. Textview= (Textview) findviewbyid (R. Id. textview01 );
  20. Button. setonclicklistener (New onclicklistener (){
  21. @ Override
  22. Public void onclick (view v ){
  23. ProgressbarasynctaskAsynctask=NewProgressbarasynctask (textview, progressbar );
  24. Asynctask.exe cute (1000 );
  25. }
  26. });
  27. }
  28. }

 

Netoperator. Java

[HTML] View plaincopy

  1. Package Vic. Wong. Main;
  2. // Simulate the Network Environment
  3. Public class netoperator {
  4. Public void operator (){
  5. Try {
  6. // Sleep for 1 second
  7. Thread. Sleep (1000 );
  8. } Catch (interruptedexception e ){
  9. // Todo auto-generated Catch Block
  10. E. printstacktrace ();
  11. }
  12. }
  13. }

 

Progressbarasynctask. Java

[HTML] View plaincopy

  1. Package Vic. Wong. Main;
  2. Import Android. OS. asynctask;
  3. Import Android. widget. progressbar;
  4. Import Android. widget. textview;
  5. /**
  6. * After the class object is generated and the execute method is called
  7. * The onproexecute method is executed first.
  8. * Second, execute the doinbackgroup method.
  9. *
  10. */
  11. Public class progressbarasynctask extends asynctask<Integer, Integer, string>{
  12. Private textview;
  13. Private progressbar;
  14. Public progressbarasynctask (textview, progressbar ){
  15. Super ();
  16. This. textview= Textview;
  17. This. progressbar= Progressbar;
  18. }
  19. /**
  20. * The integer parameter corresponds to the first parameter in asynctask.
  21. * The string return value corresponds to the third parameter of asynctask.
  22. * This method is not run in the UI thread and is mainly used for asynchronous operations. All spaces in the UI cannot be set or modified in this method.
  23. * However, you can call publishprogress to trigger onprogressupdate to operate the UI.
  24. */
  25. @ Override
  26. Protected string doinbackground (integer... Params ){
  27. NetoperatorNetoperator=NewNetoperator ();
  28. IntI=0;
  29. For (I=10; I<= 100; I + = 10 ){
  30. Netoperator. Operator ();
  31. Publishprogress (I );
  32. }
  33. Return I + Params [0]. intvalue () + "";
  34. }
  35. /**
  36. * The string parameter corresponds to the third parameter in asynctask (that is, receiving the return value of doinbackground)
  37. * After the doinbackground method is executed, it runs in the UI thread. You can set the UI space.
  38. */
  39. @ Override
  40. Protected void onpostexecute (string result ){
  41. Textview. settext ("Asynchronous Operation execution ends" + result );
  42. }
  43. // This method runs in the UI thread and can be set in the UI thread.
  44. @ Override
  45. Protected void onpreexecute (){
  46. Textview. settext ("Starting asynchronous thread execution ");
  47. }
  48. /**
  49. * The intege parameter corresponds to the second parameter in asynctask.
  50. * In the doinbackground method, each call to the publishprogress method triggers the onprogressupdate execution.
  51. * Onprogressupdate is executed in the UI thread. All operations can be performed on the UI space.
  52. */
  53. @ Override
  54. Protected void onprogressupdate (integer... values ){
  55. IntVlaue=Values[0];
  56. Progressbar. setprogress (vlaue );
  57. }
  58. }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.