Android 异步请求通用类

package com.example.demo1;

import java.util.EventListener;

public interface MyAsyncTaskListener extends EventListener 
{
    public Object Task(Object... parameters);
    public void TaskCompleted(Object result);
}
package com.example.demo1;

import android.os.AsyncTask;

public class MyAsyncTask extends AsyncTask<Object, Void, Object> {
    
    private MyAsyncTaskListener myAsyncTaskListeners = null;
    
    @Override
    protected Object doInBackground(Object... params) {
        if(myAsyncTaskListeners != null)
            return myAsyncTaskListeners.Task(params);
        else
            return null;
    }

    @Override
    protected void onPostExecute(Object result) {
        if(myAsyncTaskListeners != null)
            myAsyncTaskListeners.TaskCompleted(result);
    }
    
    public void setAsyncTaskListener(MyAsyncTaskListener listener)
    {
        myAsyncTaskListeners = listener;
    }
}
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new 
                StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
                        StrictMode.setVmPolicy(
                new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        
                        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final ImageView image = (ImageView)this.findViewById(R.id.image);
        
        MyAsyncTask task = new MyAsyncTask();
        task.setAsyncTaskListener(new MyAsyncTaskListener() {
            @Override
            public Object Task(Object... parameters) {
                try {
                    File file = downloadFile(parameters[0].toString());
                    TiffDecoder.nativeTiffOpen(file.getPath());
                    int[] pixels = TiffDecoder.nativeTiffGetBytes();
                    Bitmap mBitmap = Bitmap.createBitmap(pixels, TiffDecoder.nativeTiffGetWidth(), TiffDecoder.nativeTiffGetHeight(),Bitmap.Config.ARGB_8888);
                    TiffDecoder.nativeTiffClose();
                    return mBitmap;
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public void TaskCompleted(Object result) {
                if(result == null)
                    return;
                
                image.setImageBitmap((Bitmap)result);
            }
        });   
        
        task.execute("http://xibei1-image.jfdedu.com/00006009b4673bbc-ff2a-49bd-91fe-764c01b2acce01.tif");
    }

private File downloadFile(String strUrl) throws IOException
    {
        URL url = new URL(strUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true); //这句不能加,会自动将请求改为POST
        urlConnection.connect();
        
        File file = File.createTempFile("myfile", ".tif", this.getCacheDir());
        if(file.exists())
            file.delete();
        file.createNewFile();

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        return file;
    }

 上面的示例干扰代码比较多,其实这个类的使用方法是这样的:

           MyAsyncTask task = new MyAsyncTask();
//定义了一个匿名类,这个匿名类继承了接口MyAsyncTaskListener,并且实例化了这个匿名类型的一个实例,传递给接口方法。 task.setAsyncTaskListener(
new MyAsyncTaskListener() { @Override public Object Task(Object... parameters) { //执行耗时操作并返回结果 } @Override public void TaskCompleted(Object result) { //接收并使用异步请求结果 } }); //开始异步请求 task.execute("http://xibei1-image.jfdedu.com/00006009b4673bbc-ff2a-49bd-91fe-764c01b2acce01.tif");

 

posted on 2018-04-19 20:24  空明流光  阅读(216)  评论(0编辑  收藏  举报

导航