Android apk 更新

基础代码工具类

package com.sampon.myapplication.widge;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.content.FileProvider;

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

import static android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES;


/**
 * APP版本升级管理
 * Created by Char on 2016/4/21.
 * 一键下载安装 通知栏也有  适配7.0 8.0 更新和 安装可以借鉴  下载可以用别的,这里是用android 自己带的 
      DownloadManager 
 * 注意下载目录是 Environment.DIRECTORY_DOWNLOADS
 */
public class AppVersionUtil {

    private Context activity;
    private DownloadManager downManager;
    private DownLoadCompleteReceiver receiver;
    private long downloadID;
    private ProgressDialog progressDialog;
    private ScheduledExecutorService ses;

    public AppVersionUtil(Context activity) {
        this.activity = activity;
    }

    public void downLoadApk(final String url) {
        if (!TextUtils.isEmpty(url)) {
            try {
                IntentFilter filter = new IntentFilter();
                filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
                filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
                receiver = new DownLoadCompleteReceiver();
                activity.registerReceiver(receiver, filter);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                //设置通知栏标题
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
                request.setTitle("下载");
                request.setDescription("正在下载");
                request.setAllowedOverRoaming(false);
                // 下载到手机/Download 目录下
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "kalebao.apk");
                downManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
                downloadID = downManager.enqueue(request);
                progressDialog = new ProgressDialog(activity);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage("下载中,请稍后...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                ses = Executors.newSingleThreadScheduledExecutor();
                ses.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        queryTaskById(downloadID);
                    }

                }, 0, 1, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean mIsShowProgress = true;


    private class DownLoadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                try {
                    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    if (downloadID == id) {
                        DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(id);
                        Cursor cursor = downManager.query(query);
                        if (cursor.moveToNext()) {
                            String downloadFilePath = null;
                            String downloadFileLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            if (downloadFileLocalUri != null) {
                                File mFile = new File(Uri.parse(downloadFileLocalUri).getPath());
                                downloadFilePath = mFile.getAbsolutePath();
                                update(downloadFilePath);
                            }

                        }
                        cursor.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            }
        }
    }

    private void queryTaskById(long downloadID) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadID);
        Cursor cursor = downManager.query(query);
        String size = "0";
        String sizeTotal = "0";
        if (cursor.moveToNext()) {
            size = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            sizeTotal = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        }
        cursor.close();
        if (mIsShowProgress && progressDialog != null) {
            progressDialog.setMax(Integer.valueOf(sizeTotal));
            progressDialog.setProgress(Integer.valueOf(size));
        }
    }

    void update(String path) {
        try {
            if (mIsShowProgress && progressDialog != null) {
                progressDialog.dismiss();
            } else {
                Toast.makeText(activity, "下载成功,正在安装", Toast.LENGTH_LONG).show();
            }
            if (ses != null) {
                ses.shutdown();
            }
            activity.unregisterReceiver(receiver);
            boolean installAllowed;
            // 8.0 需要安装未知来源应用权限  <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                installAllowed = activity.getPackageManager().canRequestPackageInstalls();
                if (installAllowed) {
                    installApk(path);
                } else {
                    Intent intent = new Intent(ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + activity.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(intent);
                    installApk(path);
                    return;
                }
            } else {
                installApk(path);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void installApk(String path) {
        // 7.0 fileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", new File(path));
            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData(apkUri);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            activity.startActivity(intent);
        } else {
            Uri apkUri = Uri.fromFile(new File(path));
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        }

    }


    /**
     * 记得在 页面 ondestory 反注册一下
     */
    public void unregister(){
     if (receiver != null && activity != null){
         activity.unregisterReceiver(receiver);
     }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。