DownloadManager升级APK并且进度显示

Android sdk version 9以上就有DownloadManager
下面就是我如何使用DownloadManager
package com.qq.beamzhang.mt.lib.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;

import com.qq.beamzhang.logic.AppConstant;
import com.qq.beamzhang.logic.api.ApiConstants;
import com.qq.beamzhang.mt.lib.util.PackageUtils;
import com.qq.dexinda.util.LogUtil;
import com.qq.dexinda.util.SharedPreferencesUtil;

import java.io.File;
import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import dexinda.qq.com.login.login.LoginFragment;

/**
 * Created by Zhongqi.Shao on 2017/1/27.
 */
public class DownUpdateService extends Service {

    private final String DOWN_RL_PATH = "androidApp/download/";
    private Handler mUiHandler;
    private DownloadManager mDownloadManager;
    private CompleteReceiver mDownReceiver;
    private UpdateBinder mUpdateBinder = null;
    private DownListener mDownListener = null;
    private DownloadChangeObserver mDownObserver = null;
    private ScheduledExecutorService mScheduleExecutor = null;
    private ProgressThread mProgressThread = null;

    private long mDownLoadId;
    private String mFileName;

    @Override
    public IBinder onBind(Intent intent) {
        return mUpdateBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mUpdateBinder = new UpdateBinder();
        mDownObserver = new DownloadChangeObserver(mUiHandler);
        mProgressThread = new ProgressThread();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (mScheduleExecutor != null) {
            mScheduleExecutor.shutdown();
        }
        if (mDownObserver != null) {
            getContentResolver().unregisterContentObserver(mDownObserver);
        }
        if (mProgressThread != null) {
            mProgressThread = null;
        }
        if (mDownReceiver != null) {
            unregisterReceiver(mDownReceiver);
        }
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class CompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == mDownLoadId) {
                DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
                myDownloadQuery.setFilterById(mDownLoadId);

                Cursor myDownload = mDownloadManager.query(myDownloadQuery);
                if (myDownload.moveToFirst()) {
                    int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                    mFileName = myDownload.getString(fileNameIdx);
                    String sizeTotal = myDownload.getString(myDownload.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    if (Long.parseLong(sizeTotal) < 0 || mFileName == null) {
                        return;
                    }
                }
                myDownload.close();
                installApk();
            }
        }
    }

    private void installApk() {
       /*Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + mFileName),
            "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);*/
        /*String command = "chmod 777 " + mFileName;
        LogUtil.i("startInstallApk", "command = " + command);
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process proc = runtime.exec(command);
        }
        catch (IOException e)
        {
            LogUtil.e("catch", e);
            e.printStackTrace();
        }*/
        int tag = PackageUtils.install(getApplicationContext(), mFileName);
        LogUtil.d("shao", "installApk: value " + tag);
    }

    private void deleteFile() {
        File file = new File("/sdcard/MT_PART/mydown.apk");
        if (file != null && file.exists() && file.isFile()) {
            file.delete();
        }
    }

    private void registerContentObserver() {
        if (mDownObserver != null) {
            getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, mDownObserver);
        }
    }

    /*
    * 通过downloadID查询下载的进度信息
    * */
    private int[] getBytesAndStatus(long downloadId) {
        final int[] bytesAndStatus = new int[]{-1, -1, 0};
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已经下载文件大小
                bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //下载文件的总大小
                bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //下载状态
                bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (mUiHandler != null && mDownListener != null) {
                    mUiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mDownListener.progressChange(bytesAndStatus[1], bytesAndStatus[0], bytesAndStatus[2]);
                        }
                    });
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return bytesAndStatus;
    }


    public class UpdateBinder extends Binder {

        public void setUiHandler(Handler uiHandler) {
            mUiHandler = uiHandler;
        }

        public void setDownListener(DownListener listener) {
            mDownListener = listener;
        }

        public void deleteApk(){
            deleteFile();
        }

        /*
        * 开始下载 http的header部分绑定cookie数据
        * */
        public void startDownLoad() {
            deleteFile();
            if (LoginFragment.SERVER_CODE == -1) {
                return;
            }
            mDownReceiver = new CompleteReceiver();
            mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            registerReceiver(mDownReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            registerContentObserver();
            String url = ApiConstants.get_Ip_Host_Gmwx() + DOWN_RL_PATH + LoginFragment.SERVER_CODE;
            //设置URL
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);
            //设置下载的路径
            request.setDestinationInExternalPublicDir("MT_PART", "mydown.apk");
            //http协议head设置cookie
            HashSet<String> cookies = (HashSet<String>) SharedPreferencesUtil.getDefault(getApplicationContext()).getStringSet(AppConstant.PREF_COOKIES, null);
            if (cookies == null || cookies.size() <= 0) {
                return;
            }
            for (String cookieHeader : cookies) {
                request.addRequestHeader("Set-Cookie", cookieHeader);
            }
            //每一个下载请求对应的downloadID标识
            mDownLoadId = mDownloadManager.enqueue(request);
            if (mUiHandler != null && mDownListener != null) {
                mUiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mDownListener.startDown();
                    }
                });
            }
        }
    }


    private class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
            mScheduleExecutor = Executors.newSingleThreadScheduledExecutor();
        }

        @Override
        public void onChange(boolean selfChange) {
            //设置查询进度的线程每隔两秒查询一下
            mScheduleExecutor.scheduleAtFixedRate(mProgressThread, 0, 2, TimeUnit.SECONDS);
        }
    }

    public class ProgressThread implements Runnable {
        @Override
        public void run() {
            getBytesAndStatus(mDownLoadId);
        }
    }


    public interface DownListener {

        void progressChange(int totalSize, int downSize, int downStatus);

        void startDown();

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值