android开发AsyncTask异步任务实例

今晚无聊,写了个AsyncTask异步下载任务;

继承AsyncTask需要实现几种方法:onPreExecute、doInBackground、onProgressUpdate、onPostExecute

分别是:开始前执行、后台任务执行、进度更新、执行完毕。

以下是MainActivity.java中onCreate()方法中的代码:

Button down = (Button)findViewById(R.id.down);
final ProgressBar pbr = (ProgressBar)findViewById(R.id.progressBar);

down.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(downTask!=null){
            AsyncTask.Status status = downTask.getStatus();
            if(status != AsyncTask.Status.FINISHED){
                Toast.makeText(MainActivity.this,"请不要重复提交下载任务",Toast.LENGTH_LONG).show();
                return;
            }
        }
        downTask = new DownTask(MainActivity.this, pbr,true);
        downTask.execute("http://192.168.1.107/1.mp3");
    }
});

//代码很简单,就是一个按钮点击事件,这里下载的是一首MP3

//以下是异步类的全部代码:

package com.lanxin.servicetest;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Alan on 2016/5/26 0026.
 */
public class DownTask extends AsyncTask<String,Integer,File> {

    private static final String TAG = "DOWNTASK";
    private Context mContext;
    private ProgressBar progressBar;
    private File root;
    private String filePath;
    private boolean is_open;


    public DownTask(Context ctx,ProgressBar pbr,boolean isopen){
        super();
        mContext = ctx;
        progressBar = pbr;
        is_open = isopen;

        filePath = "downTask";//下载的目录

        root = Environment.getExternalStorageDirectory();

        checkDir(filePath);


    }

    /**
     * 开始执行后台下载任务
     * @param urls
     * @return
     */
    protected File doInBackground(String... urls) {
        Log.i(TAG, "doInBackground");

        return downTemp(urls);
    }

    /**
     * 开始之前操作
     */
    protected void onPreExecute() {
        Log.i(TAG,"onPreExecute");
        progressBar.setProgress(0);

    }

    /**
     * 用户取消时执行
     */
    protected void onCancelled() {
        Log.i(TAG, "onCancelled");
    }

    /**
     * 更新进度条
     * @param state
     */
    protected void onProgressUpdate(Integer... state) {
        Log.i(TAG,"onProgressUpdate:"+state[0]);

        progressBar.setProgress(state[0]);

    }

    protected void onPostExecute(File result) {
        if(result!=null){
            Log.i(TAG, "onPostExecute");
            if(is_open){openFile(result);}

        }else{
            Log.i(TAG,"error:onPostExecute");
        }

    }

    private File downTemp(String... urls){
        String _name = urls[0].substring(urls[0].lastIndexOf("/"));

        try {
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            int fileLength = conn.getContentLength();

            int totalLength = 0;
            int length = 0;

            InputStream in = conn.getInputStream();
            FileOutputStream out = new FileOutputStream(new File(getDir(),_name));

            byte[] buff = new byte[1024*1024];
            while ((length=in.read(buff))>0){

                totalLength += length;
                int press = (int)(totalLength*100)/fileLength;

                publishProgress(press);

                out.write(buff,0,length);

            }
            in.close();
            out.flush();
            out.close();

            return new File(getDir(),_name);

        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 检查目录是否存在,如果不存在则创建
     * @param name
     * @return
     */
    public boolean checkDir(String name){
        if("".equals(name)){
            return false;
        }


        File newFile = new File(root+"/"+name+"/");
        Log.i(TAG,root+"/"+name+"/");

        if(!newFile.exists()){
            return newFile.mkdirs();
        }
        return true;
    }

    /**
     * 取出下载目录
     * @return
     */
    public String getDir(){
        return root+"/"+filePath+"/";
    }

    /**
     * 打开文件
     * @param file
     */
    public void openFile(File file){
        Intent intent = new Intent();

        String fileName = file.getAbsolutePath();
        if(fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "image/*");
            mContext.startActivity(intent);

        }else if(fileName.endsWith(".mp4")
                || fileName.endsWith(".3gp")
                || fileName.endsWith(".avi")
                || fileName.endsWith(".flv")
                || fileName.endsWith(".wmv")
                || fileName.endsWith(".rmvb")
                || fileName.endsWith(".asf")
                || fileName.endsWith(".mkv")
                || fileName.endsWith(".mpg")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "video/*");
            mContext.startActivity(intent);
        }else if(fileName.endsWith(".mp3")
                || fileName.endsWith(".ogg")
                || fileName.endsWith(".ape")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "audio/*");
            mContext.startActivity(intent);
        }else if(fileName.endsWith(".apk")){
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

}

 

有了这2段代码别忘记了申明权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

Leave a Comment