Android Asynctack Asynchronous Task example detailed _php tips

Source: Internet
Author: User

Android Asynctack Asynchronous task

Here is a small example of how to consolidate the knowledge of the Android Asynctack asynchronous task for use in the project.

Describe how to use

1, inheriting Asynctask

public class MyTask extends Asynctask<params, Progrss, result>

Let's take a look at the role of these three generics:

Params: The type that is passed in when the asynchronous task is invoked;

Progress: The literal meaning is the progress bar, which is actually the type of the dynamic publish data to the main thread.

Result: Returns the type of results

2, rewrite the abstract method of this class Doinbackground, of course it also has several methods to rewrite, we all see

Doinbackground (abstract method, must be implemented)

/* The only way to execute in a child thread
 *  so no UI updates
 * @param params
 * @return * *
@Override//return value: Result    parameter: Param
protected String doinbackground (TextView ... params) {
  text = params[0];
  Random Random = new Random ();
  for (int i = 0; i < i++) {
    //update publishprogress for Progress
    (i);
    You cannot call the Onprogressupdate method directly,
    //This will cause Onprogressupdate to run
    try {
      Thread.Sleep (10) in a child thread *);
    catch (Interruptedexception e) {
      e.printstacktrace ();
    }
  }
  return "Completed";
}

The following three methods choose to use depending on the situation

 Call
  @Override
  protected void OnPreExecute () {
    super.onpreexecute ()
  } before executing doinbackground

  The @Override//publishprogress (i) corresponds to the
  protected void onprogressupdate (Integer ... values) {
    Super.onprogressupdate (values);
    Text.settext (String.valueof (values[0]));
  }


 Execute after Doinbackground
  @Override//parameter S is result
  protected void OnPostExecute (String s) {
    Super.onpostexecute (s);
    Text.settext (s);
  }

3, performing asynchronous tasks

There are two ways I've written the distinction in the comments/
*
 Direct execute asynchronous task, which is the same thread to execute
/

Text = (TextView) Findviewbyid (r.id.main_ Text1);
New MyTask (). Execute (text);
Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT2);
New MyTask (). Execute (text);
Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT3);
New MyTask (). Execute (text);
Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT4);
New MyTask (). Execute (text);

/*
  start multiple threads to perform asynchronous tasks
  API11 above can be used
* *
 scheduledthreadpoolexecutor executor = new Scheduledthreadpoolexecutor (4);
 Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT1);
 New MyTask (). Executeonexecutor (executor, text);
 Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT2);
 New MyTask (). Executeonexecutor (executor, text);
 Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT3);
 New MyTask (). Executeonexecutor (executor, text);
 Text = (TextView) Findviewbyid (R.ID.MAIN_TEXT4);
 New MyTask (). Executeonexecutor (executor, text);

Note: If we go directly to execute our task, it (the task) will only run on the same child thread, so when the first of these methods is started, four tasks are executed sequentially (that is, one task is executed and another is executed); The second way, it creates a thread pool, which automatically creates a new child thread for it, all tasks are not sequential, but several threads "execute simultaneously"

Get network data present in WebView and download pictures and their coexistence cases

1, first we have to come to a layout, the specific requirements are such, on the WebView has a imageview, and, ImageView can roll with WebView, so this time we think of the use of ScrollView, but we must not forget, ScrollView can only contain one control, so we can wrap it in linearlayout

<scrollview
  android:layout_width= "match_parent"
  android:layout_height= "match_parent" >
  < LinearLayout
    android:orientation= "vertical"
    android:layout_width= "match_parent"
    android:layout_ height= "Match_parent" >
    <imageview
      android:id= "@+id/main2_image" android:layout_width= "WRAP_"
      Content "
      android:layout_height=" wrap_content "/>
    <webview
      android:id=" @+id/main2_web "
      android:layout_width= "match_parent"
      android:layout_height= "match_parent"/>
  </ Linearlayout>
</ScrollView>

2, next we need to have an entity class for storing content downloaded from a Web page (the reason for this is that we want to use Gson to parse the content from the Web page).

public class Entry {
  @SerializedName ("title")
  private String title;
  @SerializedName ("message") a
  private String message;
  @SerializedName ("img")
  private String image;

  Public String GetTitle () {return
    title;
  }
  .//Omit remaining getter and setter methods public
  void SetImage (String image) {
    this.image = image;
  }
}

3, then we solve the problem is how to download the picture? How do I download Web content? , then we write two generic tool classes

Download tool class (common type)

/** * Created by Lulu on 2016/8/31. * <p/> * Universal Download Tool Class * * public class networktask<t> extends Asynctask<networktask.callback<t>, Void, Ob
  ject> {private networktask.callback<t> Callback;
  Private class<t> T;

  Private String URL;
    Public networktask (String URL, class<t> T) {this.url = URL;
  THIS.T = t;

    } @Override protected Object doinbackground (callback<t>. params) {Callback = params[0];
      try {httpurlconnection connection = (httpurlconnection) new URL (URL). OpenConnection ();
      Connection.setrequestmethod ("get");
      Connection.setdoinput (TRUE);
      int code = Connection.getresponsecode ();
        if (code = =) {InputStream is = Connection.getinputstream ();
        Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
        byte[] buffer = new byte[102400];
        int length;
        while (length = is.read (buffer))!=-1) {bos.write (buffer, 0, length); }
        Return bos.tostring ("UTF-8");
      else {return new RuntimeException ("Server Exception");
      } catch (Exception e) {e.printstacktrace ();
    return e;
    } @Override protected void OnPostExecute (Object o) {super.onpostexecute (o);
      if (o instanceof string) {string str = (string) o;
      Gson Gson = new Gson ();
      t = Gson.fromjson (str, THIS.T);
    Callback.onsuccess (t);
      } if (o instanceof Exception) {Exception e = (Exception) o;
    Callback.onfailed (e);
    } public interface Callback<s> {void onsuccess (S t);
  void onfailed (Exception e);

 }
}

Picture Loader (common type)

/** * Created by Lulu on 2016/8/31. * Image Network Loader * Download successful return BITMAP * otherwise return NULL/public class Imageloader extends Asynctask<string, Void, bitmap>{Priva

  Te ImageView image;
    Public Imageloader (ImageView image) {this.image = image;
  Image.setimageresource (R.mipmap.ic_launcher);

  } @Override protected void OnPreExecute () {super.onpreexecute ();
    @Override protected Bitmap doinbackground (String ... params) {string url = params[0];
      try {httpurlconnection connection = (httpurlconnection) new URL (URL). OpenConnection ();
      Connection.setrequestmethod ("get");
      Connection.setdoinput (TRUE);
      int code = Connection.getresponsecode ();
        if (code = =) {InputStream is = Connection.getinputstream ();
      Return Bitmapfactory.decodestream (IS);
    } catch (IOException e) {e.printstacktrace ();
  return null; } @Override protected void OnPostExecute (Bitmap Bitmap) {Super.onpostexecute (b)ITMAP);
    if (bitmap!= null) {Image.setimagebitmap (bitmap);
    else {image.setimageresource (r.mipmap.failed);

 }
  }
}

4, Test activity

Note: See How to solve the big picture in the webview not about sliding problem!

public class Main2activity extends appcompatactivity implements networktask.callback<entry>{private WebView web;
  Private ImageView image;
  Solve the problem that the large graph does not slide about in WebView private static final String CSS = "<style>img{max-width:100%} </style>";
  Private String title;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main2);
    web = (webview) Findviewbyid (R.id.main2_web);
    Image = (ImageView) Findviewbyid (r.id.main2_image);
  New Networktask<> ("http://www.tngou.net/api/top/show?id=13122", Entry.class). Execute (this); @Override public void onsuccess (Entry t) {Web.loaddatawithbaseurl ("", T.getmessage (), text/html;
    Charset=utf-8 "," UTF-8 ", null);
  New Imageloader (image). Execute ("http://img.blog.csdn.net/20160829134937003"); @Override public void onfailed (Exception e) {Web.loaddatawithbaseurl ("", "Failed to load", "text/html; Charset=utf-8 "," UTF-8", null);

 }
}

5. Effect Chart:

Thank you for reading, I hope to help you, thank you for your support for this site!

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.