android两种方式获取AsyncTask返回值

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


1.

布局文件:

    
   
    
    
 

2.

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 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.

回调接口:
public interface OnDataFinishedListener {
     
    public void onDataSuccessfully(Object data);
     
    public void onDataFailed();
     
}


4.
第二种:使用handler:
 
1.修改ImageViewAsyncTask:
public class ImageViewAsyncTask extends AsyncTask {
     
    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;
            }
        }
         
    };


你可能感兴趣的:(Android基础)