封装一个方法来使用异步任务类进行网络操作之回调方法

1.首先是权限的声明

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bwf.callback"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.bwf.callback.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

 

 1 package com.bwf.callback;
 2 
 3 import org.apache.http.HttpResponse;
 4 import org.apache.http.client.HttpClient;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.impl.client.DefaultHttpClient;
 7 import org.apache.http.util.EntityUtils;
 8 
 9 import android.content.Context;
10 import android.graphics.Bitmap;
11 import android.graphics.BitmapFactory;
12 import android.os.AsyncTask;
13 import android.util.Log;
14 
15 public class ImgLoader {
16     Context context;
17     CallBack mCallBack;
18     
19     public ImgLoader(Context context) {
20         super();
21         this.context = context;
22     }
23 
24     interface CallBack{
25         boolean onLoad(Bitmap bmp);
26     }
27     
28     /**
29      * 封装一个方法来使用异步任务类进行网络操作
30      * */
31     public void download(String path, CallBack mCallBack){
32         this.mCallBack = mCallBack;
33         MyAsync myAsync = new MyAsync();
34         myAsync.execute(path);
35     }
36     
37     
38     class MyAsync extends AsyncTask<String, Void, Bitmap>{
39         
40         /**
41          * 网络操作
42          * */
43         @Override
44         protected Bitmap doInBackground(String... params) {
45             // TODO Auto-generated method stub
46             String str = params[0];
47             HttpClient client = new DefaultHttpClient();
48             HttpGet get = new HttpGet(str);
49             HttpResponse response;
50             try {
51                 response = client.execute(get);
52                 int code = response.getStatusLine().getStatusCode();
53                 if(code == 200){
54                     byte[] arr = EntityUtils.toByteArray(response.getEntity());
55                     Bitmap bmp = BitmapFactory.decodeByteArray(arr, 0, arr.length);
56                     return bmp;
57                 } else{
58                     Log.d("fanhy", "状态码为:"+code);
59                 }
60             } catch (Exception e) {
61                 // TODO Auto-generated catch block
62                 Log.d("fanhy", e.toString());
63             }
64             
65             return null;
66         }
67         
68         /**
69          * 得到网络任务的结果
70          * */
71         @Override
72         protected void onPostExecute(Bitmap result) {
73             // TODO Auto-generated method stub
74             super.onPostExecute(result);
75             
76             mCallBack.onLoad(result);
77         }
78     }
79 }

2.

 1 package com.bwf.callback;
 2 
 3 import com.bwf.callback.ImgLoader.CallBack;
 4 
 5 import android.os.Bundle;
 6 import android.app.Activity;
 7 import android.graphics.Bitmap;
 8 import android.view.Menu;
 9 import android.view.MenuItem;
10 import android.widget.ImageView;
11 
12 public class MainActivity extends Activity {
13     private String path="http://www.qiuyongsheng.com/static/index/baidu.jpg";
14     ImageView iv;
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19         
20         iv = (ImageView) findViewById(R.id.iv);
21     }
22 
23     @Override
24     public boolean onCreateOptionsMenu(Menu menu) {
25         // Inflate the menu; this adds items to the action bar if it is present.
26         getMenuInflater().inflate(R.menu.main, menu);
27         return true;
28     }
29 
30     @Override
31     public boolean onOptionsItemSelected(MenuItem item) {
32         switch (item.getItemId()) {
33         case R.id.action_settings:
34             ImgLoader loader = new ImgLoader(this);
35             loader.download(path, new CallBack() {
36                 
37                 @Override
38                 public boolean onLoad(Bitmap bmp) {
39                     iv.setImageBitmap(bmp);
40                     return false;
41                 }
42             });
43             break;
44 
45         default:
46             break;
47         }
48         return super.onOptionsItemSelected(item);
49     }
50 }

 

posted on 2015-10-20 09:06  敬的男人  阅读(152)  评论(0)    收藏  举报