1. 程式人生 > >Android多執行緒下載APk+自動安裝

Android多執行緒下載APk+自動安裝

DialogUtils 
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;

import com.example.dell.dierzhouzhoukao.net.DownloadThread;

import 
java.io.File; import java.io.IOException; public class DialogUtils { public static long MAX_SIZE = 0; public static long PROGRESS = -2; private static File file; private static String path; public static void showUpdataDialog(final Context context){ AlertDialog.Builder builder = new
AlertDialog.Builder(context); builder.setTitle("是否下載") .setMessage("下載檔案") .setNegativeButton("不下載", null) .setPositiveButton("下載", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int
i) { path = context.getCacheDir() + "/自己給一個名字"; new DownloadThread("下載的網址",path ).start(); showProgress(context); } }).show(); } public static void showProgress(final Context context){ final ProgressDialog pd = new ProgressDialog(context); pd.setTitle("正在下載"); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMax(100); pd.show(); new AsyncTask<String, Integer, String>(){ @Override protected String doInBackground(String... strings) { while (PROGRESS + 1 < MAX_SIZE){ SystemClock.sleep(100); if(MAX_SIZE > 0 ){ publishProgress((int)(PROGRESS * 100 / MAX_SIZE)); } } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); pd.dismiss(); file = new File(path); System.out.println(file.length()+"====="); openApk(context,file); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); pd.setProgress(values[0]); } }.execute(); } public static void openApk(Context context,File file) { String[] command = {"chmod", "777", file.getPath() }; ProcessBuilder builder = new ProcessBuilder(command); try { builder.start(); } catch (IOException e) { e.printStackTrace(); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } } Netutils
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtils {
    public static void downloadFile(String downloadUrl, String path, int blockSize, int startPosition){
        BufferedInputStream bis = null;
        RandomAccessFile raf = null;
        try {
            File f = new File(path);
            if(!f.exists()){
                f.createNewFile();
            }
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(8000);
            conn.setConnectTimeout(8000);
if(blockSize > 0){long end = blockSize + startPosition - 1;
conn.setRequestProperty("Range", "bytes=" + startPosition + "-" + end);

                Log.i(Thread.currentThread() + "======", "bytes=" + startPosition + "-" + end);
            }


            int code = conn.getResponseCode();
            if(code < 400){
                bis = new BufferedInputStream(conn.getInputStream());
                raf = new RandomAccessFile(f, "rwd");
                //
raf.seek(startPosition);
                //
int len = 0;
                byte[] buff = new byte[1024 * 8];
                while((len = bis.read(buff)) != -1){
                    synchronized (NetUtils.class){
                        raf.write(buff, 0, len);
                        if(DialogUtils.PROGRESS < 0){
                            DialogUtils.PROGRESS = 0;
                        }
                        DialogUtils.PROGRESS += len;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static int getFileLength(String downloadUrl){
        int len = 0;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(8000);
            conn.setConnectTimeout(8000);

            len = conn.getContentLength();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return len;
    }
}
DownloadThread
public class DownloadThread extends Thread{
    private String downloadUrl = "";
    private String path;
    private int threadNum = 2;

    public DownloadThread(String downloadUrl, String path) {
        this.downloadUrl = downloadUrl;
        this.path = path;
    }

    @Override
public void run() {
        int len = NetUtils.getFileLength(downloadUrl);
        DialogUtils.MAX_SIZE = len;
int blockSize = len/threadNum;
for (int i = 0; i < threadNum; i++) {
int startPosition = blockSize * i;
 if(i == threadNum - 1){
                blockSize = len - blockSize * (threadNum - 1);
            }
            new DownloadTask(downloadUrl, path, blockSize, startPosition).start();
        }


    }

    public void setThreadNum(int threadNum){
        this.threadNum = threadNum;
    }
}
DownloadTask
public class DownloadTask extends Thread{
    String downloadUrl;
    String path;
    int blockSize;
    int startPosition;

    public DownloadTask(String downloadUrl, String path, int blockSize, int startPosition) {
        this.downloadUrl = downloadUrl;
        this.path = path;
        this.blockSize = blockSize;
        this.startPosition = startPosition;
    }

    @Override
public void run() {
        NetUtils.downloadFile(downloadUrl,path,blockSize,startPosition);
    }
}
MainAcyivity
DialogUtils.showUpdataDialog(this);