系统下载管理器DownloadManager下载,安装apk

首先学习下FileProvider

看这里 https://www.jianshu.com/p/e05f35fbb569

整理下方便用到的时候直接copy,先这样,以后有空再改。

安装的代码

权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

fun installCheck(context: Context,file: File) {
        if (!file.exists()) {
            return
        }
        //下边这部分不一定需要
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (context.getPackageManager().canRequestPackageInstalls()) {

            } else {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName()))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
                return
            }
        }
        installApk(context, file)
    }

    //安装apk,兼容7.0
    private fun installApk(context: Context, file: File) {
        if (!file.exists()) {
            return
        }
        val intent = Intent(Intent.ACTION_VIEW)
        // 没有在Activity环境下启动Activity,设置下面的标签
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        var uri: Uri
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址和清单文件中保持一致   参数3 共享的文件
            uri = FileProvider.getUriForFile(context, "com.charlie.fileProvider", file)
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            uri = Uri.fromFile(file)
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        // intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");

        context.startActivity(intent)
    }

FileProvider的配置

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.charlie.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths">
            </meta-data>
        </provider>

file_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!--Context.getFilesDir().-->
    <files-path
        name="filepath"
        path="filepath"/>

    <!-- getCacheDir().-->
    <cache-path
        name="cachepath"
        path="cachepath"/>

    <!-- Environment.getExternalStorageDirectory().-->
    <external-path
        name="externalpath"
        path="/"/>

    <!-- Context.getExternalCacheDir().  -->
    <external-cache-path
        name="externalcachepath"
        path="externalcachepath"/>

    <!--Context#getExternalFilesDir(String) Context.getExternalFilesDir(null).   -->
    <external-files-path
        name="externalfilespath"
        path="externalfilespath"/>

</paths>

使用系统下载

工具类

import java.io.File;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

public abstract class FileDownManager {

    private DownloadManager downloadManager;
    private String fileName;
    private String saveDir;
    public static String DOWNLOAD_SP_NAME = "download_sp_name";
    public Context mContext;
    public abstract Context getContext();

    public SharedPreferences getSp() {
        return getContext().getSharedPreferences(DOWNLOAD_SP_NAME, Context.MODE_PRIVATE);
    }

    public abstract String savedFileName(String url, String newVersion);

    public abstract String savedFileDir();

    public File getSavedFile() {
        return new File(Environment.getExternalStorageDirectory(),saveDir+"/"+fileName);
    }
    public static String downloadKey = "downID";
    public static String downloadVersionKey = "version";

    public long getDownloadID() {
        return getSp().getLong(downloadKey, -1);
    }
    public String getDownloadVersion() {
        return getSp().getString(downloadVersionKey, "0");
    }
    public void downOrSuccessAction(String url, String newVersion) {
        saveDir = savedFileDir();
        fileName = savedFileName(url, newVersion);
        downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
        String downVersion = getSp().getString(downloadVersionKey, null);
        if (TextUtils.equals(newVersion, downVersion)) {
            long id = getSp().getLong(downloadKey, -1);
            if (id == -1) {
                down(url, newVersion);
            } else {
                query(url, id, newVersion);
            }
        } else {
            getSp().edit().putString(downloadVersionKey, newVersion).commit();

            down(url, newVersion);
        }
    }

    private void down(String url, String newVersion) {

        Uri resource = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(resource);
        request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        // set file mime type
        // MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        // String mimeString =
        // mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        // request.setMimeType(mimeString);
        // show notification on the state bar
        request.setVisibleInDownloadsUi(true);
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // set the saving file's directory and name
        request.setDestinationInExternalPublicDir(saveDir, fileName);
        requestCustom(request);
        try {
            long id = downloadManager.enqueue(request);
            getSp().edit().putLong(downloadKey, id).commit();
        } catch (Exception e) {
            e.printStackTrace();
            enableDownloadManager(getContext());
        }
    }

    public void requestCustom(DownloadManager.Request request) {

    }

    private void query(String url, long id, String newVersion) {
        System.out.println("query========="+url+"==="+id+"==="+newVersion);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = downloadManager.query(query);
        if(c==null) {
            System.out.println("cursor null============");
            redownload(url, id, newVersion);//download record history was cleared
        }
        else if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
            case DownloadManager.STATUS_PAUSED:
                Log.v("down", "STATUS_PAUSED");
            case DownloadManager.STATUS_PENDING:
                Log.v("down", "STATUS_PENDING");
            case DownloadManager.STATUS_RUNNING:
                Log.v("down", "STATUS_RUNNING");
                break;
            case DownloadManager.STATUS_SUCCESSFUL:
                Log.v("down", "STATUS_SUCCESSFUL");
                String name=c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                String uri=c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                String uri_d=c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));//the http url address
                //name=/storage/emulated/0/justdelete/apkdown/appname1.2.apk
                //file:///storage/emulated/0/justdelete/apkdown/appname1.2.apk
                File savedFile=getSavedFile();
                System.out.println("name="+name+"=="+uri+"==="+uri_d+"====="+savedFile.getAbsolutePath());
                if (savedFile.exists()) {
                    downloadSuccess(savedFile);
                } else {
                    System.out.println("file not exist");
                    redownload(url, id, newVersion);
                }
                break;
            case DownloadManager.STATUS_FAILED:
                Log.v("down", "STATUS_FAILED");
                redownload(url, id, newVersion);
                break;
                default:
                    Log.v("down", "STATUS_====="+status);
                    break;
            }
        }else {
            System.out.println("===================cursor size 0");
            redownload(url, id, newVersion);
        }
    }

    private void redownload(String url, long id, String newVersion) {
        // if file not exist or download failed,redownload.
        downloadManager.remove(id);
        getSp().edit().remove(downloadKey).commit();
        down(url, newVersion);
    }

    protected void downloadSuccess(File downloadFile) {
        System.out.println("downloadfile size======"+downloadFile.length());
    }

    public static void enableDownloadManager(Context context) {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:com.android.providers.downloads"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

}

然后对于不同的下载类型继承工具类,修改key值即可
如下举了2种例子,一种下载apk,一种下载一个zip文件

apk类型下载

import java.io.File;
import android.content.Context;

public class APKDownloadManager extends FileDownManager{
    public static APKDownloadManager apkDownloadManager;
    public static APKDownloadManager getInstance(Context context) {
        if(apkDownloadManager==null) {
            synchronized (APKDownloadManager.class) {
                if(apkDownloadManager==null) {
                    apkDownloadManager=new APKDownloadManager();
                }
            }
        }
        apkDownloadManager.mContext=context;
        return apkDownloadManager;
    }
    public APKDownloadManager() {
        downloadKey="apk_down_id";
        downloadVersionKey="apk_version";
    }
    @Override
    public Context getContext() {
        if(mContext==null) {
            mContext=MyApplication.application;
        }
        return mContext;
    }

    @Override
    public String savedFileDir() {
        return "justdelete/apkdown";
    }

    @Override
    public String savedFileName(String url, String newVersion) {
        return "appname"+newVersion+".apk";
    }

    @Override
    protected void downloadSuccess(File downloadFile) {
        super.downloadSuccess(downloadFile);
        //安裝apk,7.0以上需要权限,并且uri获取也需要fileprovider
        System.out.println("apk download success================="+downloadFile.getAbsolutePath());
    }
}

zip文件类型下载

import java.io.File;
import android.content.Context;

public class MapDownloadManager extends FileDownManager{
    public static MapDownloadManager mapDownloadManager;
    public static MapDownloadManager getInstance(Context context) {
        if(mapDownloadManager==null) {
            synchronized (MapDownloadManager .class) {
                if(mapDownloadManager==null) {
                    mapDownloadManager=new MapDownloadManager();
                }
            }
        }
        mapDownloadManager.mContext=context;
        return mapDownloadManager;
    }

    public MapDownloadManager() {
        downloadKey="map_down_id";
        downloadVersionKey="map_version";
    }
    @Override
    public Context getContext() {
        if(mContext==null) {
            mContext=MyApplication.application;
        }
        return mContext;
    }

    @Override
    public String savedFileName(String url, String newVersion) {
        return "map"+newVersion+".zip";
    }

    @Override
    public String savedFileDir() {
        return "justdelete/savedMap";
    }

    
    @Override
    protected void downloadSuccess(File downloadFile) {
        //map download success
        System.out.println("map download success=============="+downloadFile.getAbsolutePath());
    }
}

然后是广播

import java.io.File;
import java.util.Arrays;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.TextUtils;

public class FileDownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("intent======action====" + intent.getAction());
        if (TextUtils.equals(intent.getAction(), DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (reference == -1) {
                return;
            }
            String filePath = getFilePath(context, reference);
            File file = new File(filePath);
            if (file.exists() && file.length() > 0) {
                APKDownloadManager apkDownloadManager =  APKDownloadManager.getInstance(context);
                if (reference == apkDownloadManager.getDownloadID()) {
                    apkDownloadManager.downloadSuccess(file);
                    return;
                }
                MapDownloadManager mapDownloadManager = MapDownloadManager.getInstance(context);
                if (reference == mapDownloadManager.getDownloadID()) {
                    mapDownloadManager.downloadSuccess(file);
                    return;
                }
            }

        } else if (TextUtils.equals(intent.getAction(), DownloadManager.ACTION_NOTIFICATION_CLICKED)) {

            long[] ids=intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            System.out.println("ids=============="+Arrays.toString(ids));
        }

    }

    private String getFilePath(Context context, long id) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).query(query);
        if (c != null && c.moveToFirst()) {
            String name = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
            return name;
        }
        return "";
    }
}

注册广播,权限添加,click那个action测试用的,可以不要

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <receiver android:name=".FileDownloadReceiver">
            <intent-filter >
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/>
            </intent-filter>
            
        </receiver>

下载代码,判断是否需要下载逻辑就看实际情况了

APKDownloadManager.getInstance(null).downOrSuccessAction("http://d2.eoemarket.com/app0/38
/38199/apk/1957269.apk?channel_id=426", "1.4");

代码说明

这个是设置下载的文件保存的文件夹,以及文件的名字的,需要注意第一个参数是sdcard根目录下的目录的名字。你可以随便起个"AAA/BBB/CCC"都可以。

request.setDestinationInExternalPublicDir(saveDir, fileName);

点到代码里看下,系统建议是用它自带的那些目录,都分门别类了,比如Environment.DIRECTORY_DOWNLOADS就是Download目录了。不过上边也说了,你随便写个目录也可以

 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
            File file = Environment.getExternalStoragePublicDirectory(dirType);

//goon
     * @param type The type of storage directory to return.  Should be one of
     * {@link #DIRECTORY_MUSIC}, {@link #DIRECTORY_PODCASTS},
     * {@link #DIRECTORY_RINGTONES}, {@link #DIRECTORY_ALARMS},
     * {@link #DIRECTORY_NOTIFICATIONS}, {@link #DIRECTORY_PICTURES},
     * {@link #DIRECTORY_MOVIES}, {@link #DIRECTORY_DOWNLOADS}, or
     * {@link #DIRECTORY_DCIM}.  May not be null.
     * 
     * @return Returns the File path for the directory.  Note that this
     * directory may not yet exist, so you must make sure it exists before
     * using it such as with {@link File#mkdirs File.mkdirs()}.
     */
    public static File getExternalStoragePublicDirectory(String type) {
        throwIfUserRequired();
        return sCurrentUser.buildExternalStoragePublicDirs(type)[0];
    }

打开下载管理器应用界面

downloadManager.enqueue(request)

上边的代码进行了异常处理,因为如果下载管理器没有启动的话,会抛出异常,我们在这里就调用下边的代码打开下载管理器页面,让用户手动启动.当然中间你可以添加一个弹框,告诉用户点击启动按钮。


image.png
    /**
     * Start activity to Settings to enable DownloadManager.
     */
    public static void enableDownloadManager(Context context) {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:com.android.providers.downloads"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

系统下载通知的一些参数说明

还可以监听通知栏的点击事件,添加如下的action即可,这个是文件没下完的时候点击事件,下载完再点击通知栏,系统会自己处理相应的文件的。

public  final static  String  ACTION_NOTIFICATION_CLICKED  = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";

下载完成的监听

<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>

通知栏可见性参数

request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);

4种:下载中可见,始终不可见,下载中和完成都可见,只有完成的时候可见

/**
         * This download is visible but only shows in the notifications
         * while it's in progress.
         */
        public static final int VISIBILITY_VISIBLE = 0;

        /**
         * This download is visible and shows in the notifications while
         * in progress and after completion.
         */
        public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;

        /**
         * This download doesn't show in the UI or in the notifications.
         */
        public static final int VISIBILITY_HIDDEN = 2;

        /**
         * This download shows in the notifications after completion ONLY.
         * It is usuable only with
         * {@link DownloadManager#addCompletedDownload(String, String,
         * boolean, String, String, long, boolean)}.
         */
        public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;

需要注意,设置不可见的时候需要权限

<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>

题外话

下边的方法可以跳转到下载历史记录页面

Intent intent=new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                startActivity(intent);
image.png

下载异常

测试的时候到jira上找个apk地址,结果下载完一直提示我解析失败,我浏览器可以正常下载啊。
后来换了个浏览器,才发现这地址需要登陆的,我默认的浏览器是登陆状态,所以可以正常下。手机端因为没有登陆,其实下了个html文件回来。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容