這里寫(xiě)一個(gè)小實(shí)例,來(lái)學(xué)習(xí)鞏固Android AsyncTack 異步任務(wù)的知識(shí),以便在項(xiàng)目中使用。
介紹一下如何使用
1, 繼承AsyncTask
public class MyTask extends AsyncTask<Params, Progrss, Result>
我們來(lái)說(shuō)一下這三個(gè)泛型的作用:
Params: 調(diào)用異步任務(wù)時(shí)傳入的類(lèi)型 ;
Progress : 字面意思上說(shuō)是進(jìn)度條, 實(shí)際上就是動(dòng)態(tài)的由子線(xiàn)程向主線(xiàn)程publish數(shù)據(jù)的類(lèi)型
Result : 返回結(jié)果的類(lèi)型
2, 重寫(xiě)這個(gè)類(lèi)的抽象方法doInBackground, 當(dāng)然它也有幾個(gè)方法需要重寫(xiě), 我們一一看來(lái)
doInBackground(抽象方法, 必須實(shí)現(xiàn))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/* 唯一執(zhí)行在子線(xiàn)程中的方法 * 所以不可以進(jìn)行UI的更新 * @param params * @return */ @Override //返回值: Result 參數(shù): Param protected String doInBackground(TextView... params) { text = params[ 0 ]; Random random = new Random(); for ( int i = 0 ; i < 50 ; i++) { //要進(jìn)行進(jìn)度的更新 publishProgress(i); //不能直接調(diào)用onProgressUpdate方法, //這樣會(huì)使得onProgressUpdate在子線(xiàn)程中運(yùn)行 try { Thread.sleep(random.nextInt( 10 ) * 10 ); } catch (InterruptedException e) { e.printStackTrace(); } } return "已完成" ; } |
下面三個(gè)方法根據(jù)具體情況選擇使用
1
2
3
4
5
|
//執(zhí)行doInBackground之前調(diào)用 @Override protected void onPreExecute() { super .onPreExecute(); } |
1
2
3
4
5
|
@Override //與publishProgress(i)對(duì)應(yīng) protected void onProgressUpdate(Integer... values) { super .onProgressUpdate(values); text.setText(String.valueOf(values[ 0 ])); } |
1
2
3
4
5
6
|
//在doInBackground之后執(zhí)行 @Override // 參數(shù)s為 Result protected void onPostExecute(String s) { super .onPostExecute(s); text.setText(s); } |
3, 執(zhí)行異步任務(wù)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
有兩種方式, 我已經(jīng)把區(qū)別寫(xiě)在了注釋中 /* 直接execute異步任務(wù), 都是同一線(xiàn)程去執(zhí)行 */ 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); |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/* 啟動(dòng)多條線(xiàn)程來(lái)執(zhí)行異步任務(wù) API11以上可以使用 */ 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); |
注意: 如果我們直接去execute我們的任務(wù), 它(任務(wù)) 只會(huì)在同一個(gè)子線(xiàn)程中運(yùn)行, 所以上述第一種方式啟動(dòng)時(shí), 四個(gè)任務(wù)順次執(zhí)行(就是一個(gè)任務(wù)執(zhí)行完了再執(zhí)行另一個(gè)); 而第二種方式, 給它創(chuàng)建了線(xiàn)程池, 這樣會(huì)自動(dòng)給它創(chuàng)建新的子線(xiàn)程, 所有的任務(wù)不是順序執(zhí)行, 而是幾個(gè)線(xiàn)程”同時(shí)執(zhí)行”
獲取網(wǎng)絡(luò)數(shù)據(jù)呈現(xiàn)在Webview和下載圖片和其共存的案例
1, 首先我們要來(lái)一個(gè)布局, 具體需求是這樣的, 在WebView之上有個(gè)ImageView, 并且, ImageView可以隨WebView滾動(dòng), 所以這個(gè)時(shí)候我們想到了用ScrollView, 但是大家一定不要忘記, ScrollView只能包含一個(gè)控件, 所以我們可以用LinearLayout包裹一下即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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, 接下來(lái)我們要有一個(gè)實(shí)體類(lèi), 用來(lái)存放從網(wǎng)頁(yè)上下載的內(nèi)容(這里加注解原因在于我們要使用GSON解析來(lái)自網(wǎng)頁(yè)的內(nèi)容)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Entry { @SerializedName ( "title" ) private String title; @SerializedName ( "message" ) private String message; @SerializedName ( "img" ) private String image; public String getTitle() { return title; } ... //省略其余getter和setter方法 public void setImage(String image) { this .image = image; } } |
3, 那我們接下解決的問(wèn)題就是 如何下載圖片? 如何下載web內(nèi)容? , 那我們寫(xiě)兩個(gè)通用的工具類(lèi)
下載工具類(lèi)(通用型)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
/** * Created by Lulu on 2016/8/31. * <p/> * 通用下載工具類(lèi) */ public class NetWorkTask<T> extends AsyncTask<NetWorkTask.Callback<T>, Void, Object> { 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 == 200 ) { 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( "服務(wù)器異常" ); } } 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 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); } } |
圖片加載器(通用型)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
/** * Created by Lulu on 2016/8/31. * 圖片網(wǎng)絡(luò)加載器 * 下載成功返回Bitmap * 否則返回null */ public class ImageLoader extends AsyncTask<String, Void, Bitmap>{ private 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 == 200 ) { InputStream is = connection.getInputStream(); return BitmapFactory.decodeStream(is); } } catch (IOException e) { e.printStackTrace(); } return null ; } @Override protected void onPostExecute(Bitmap bitmap) { super .onPostExecute(bitmap); if (bitmap != null ) { image.setImageBitmap(bitmap); } else { image.setImageResource(R.mipmap.failed); } } } |
4, 測(cè)試Activity
注意: 看如何解決大圖在webView中不左右滑動(dòng)的問(wèn)題!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class Main2Activity extends AppCompatActivity implements NetWorkTask.Callback<Entry>{ private WebView web; private ImageView image; //解決大圖在webView中不左右滑動(dòng)的問(wèn)題 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( "" , "加載失敗" , "text/html; charset=utf-8" , "UTF-8" , null ); } } |
5.效果圖:
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!