android两种方式获取AsyncTask返回值

获取AsyncTask返回值,在Activity中使用。

引用链接:https://www.oschina.net/code/snippet_725438_49858#72630

[1].[代码] [Java]代码 跳至 [1] [2] [3] [4]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
    
   <ImageView android:id="@+id/im1"
      android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/ic_launcher" />
    
    <ImageView android:id="@+id/im2"
      android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/ic_launcher" />
 
</LinearLayout>
 

[2].[代码] [Java]代码 跳至 [1] [2] [3] [4]

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
2.第一种,回调方法方式:
package com.androidwallpaper;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener{
     
     
    ImageView im1;
    ImageView im2;
     
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        im1 = (ImageView) findViewById(R.id.im1);
        im2 = (ImageView) findViewById(R.id.im2);
         
        try {
            final ImageViewAsyncTask task = new ImageViewAsyncTask("http://static.oschina.net/uploads/ad/new_banner_one_ronglianyun_WrqUs.png");
            task.setOnDataFinishedListener(new OnDataFinishedListener() {
                 
                @Override
                public void onDataSuccessfully(Object data) {
                    try {
                        im1.setImageBitmap((Bitmap) data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onDataFailed() {
                    Toast.makeText(MainActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
                }
            });
            task.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
         
         
         
    }
 
     
    class ImageViewAsyncTask extends AsyncTask<String, Integer, Bitmap> {
         
        String mUrl;
        OnDataFinishedListener onDataFinishedListener;
         
        public ImageViewAsyncTask(String url){
            this.mUrl = url;
        }
         
         
 
        public void setOnDataFinishedListener(
                OnDataFinishedListener onDataFinishedListener) {
            this.onDataFinishedListener = onDataFinishedListener;
        }
 
 
        @Override
        protected Bitmap doInBackground(String... params) {
            InputStream ins = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(mUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    ins = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(ins);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(ins!=null){
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }
 
        @Override
        protected void onPostExecute(Bitmap result) {
            progressBar.setVisibility(View.GONE);
            if(result!=null){
                onDataFinishedListener.onDataSuccessfully(result);
            }else{
                onDataFinishedListener.onDataFailed();
            }
        }
 
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
         
    }
}
 

[3].[代码] [Java]代码 跳至 [1] [2] [3] [4]

1
2
3
4
5
6
7
8
回调接口:
public interface OnDataFinishedListener {
     
    public void onDataSuccessfully(Object data);
     
    public void onDataFailed();
     
}
 

[4].[代码] [Java]代码 跳至 [1] [2] [3] [4]

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
第二种:使用handler:
 
1.修改ImageViewAsyncTask:
public class ImageViewAsyncTask extends AsyncTask<String, Integer, Bitmap> {
     
    String mUrl;
    Handler mHandler;
     
    public ImageViewAsyncTask(String url,Handler handler){
        this.mUrl = url;
        this.mHandler = handler;
    }
 
    @Override
    protected Bitmap doInBackground(String... params) {
        InputStream ins = null;
        Bitmap bitmap = null;
        try {
            URL url = new URL(mUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                ins = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(ins);
                return bitmap;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(ins!=null){
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
 
    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        Message msg = mHandler.obtainMessage();
        if(result!=null){
            msg.what = 1;
            msg.obj = result;
        }else{
            msg.what = 2;
        }
        mHandler.sendMessage(msg);
    }
 
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }
 
     
     
}
2.调用方式:
ImageViewAsyncTask task2 = new ImageViewAsyncTask("http://static.oschina.net/uploads/ad/new_banner_one_ronglianyun_WrqUs.png", handler);
        task2.execute();
 
Handler handler = new Handler(){
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                Bitmap bitmap = (Bitmap) msg.obj;
                im2.setImageBitmap(bitmap);
                break;
 
            default:
                break;
            }
        }
         
    };
原文地址:https://www.cnblogs.com/yzycoder/p/6103463.html