Android开发:使用DownloadManager在service中下载并安装apk

之前一直在CSND发布文章,不过慢慢被简书的排版布局所吸引,打算迁到这个平台,这个是第一篇文章

下载并安装apk的方法很多,最好的方法是放在service中处理,这样在页面切换或者程序退出的时候,仍然可以正常的下载并弹出安装窗口。写下来主要是给自己留给备份,同时可作为分享用。

代码比较简单,分如下几块:

启动下载

private void startDownload() {
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse("http://d.koudai.com/com.koudai.weishop/1000f/weishop_1000f.apk"));
    request.setMimeType("application/vnd.android.package-archive");
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myApp.apk");
    enqueue = dm.enqueue(request);
}

然后是监听下载完成的Receive

receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
                    "application/vnd.android.package-archive");
            startActivity(intent);
            stopSelf();
        }
    };

在监听到下载的文件后,会调用stopSelf自动关闭该service

然后,就是在activity中,启动该service

startService(new Intent(context, DownloadService.class));

完整的代码如下:

public class DownloadService extends Service {
private DownloadManager dm;
private long enqueue;
private BroadcastReceiver receiver;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
                    "application/vnd.android.package-archive");
            startActivity(intent);
            stopSelf();
        }
    };

    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    startDownload();
    return Service.START_STICKY;
}

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

private void startDownload() {
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse("http://d.koudai.com/com.koudai.weishop/1000f/weishop_1000f.apk"));
    request.setMimeType("application/vnd.android.package-archive");
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myApp.apk");
    enqueue = dm.enqueue(request);
}

}

很简单的一篇文章,希望对大家有所帮助

    原文作者:韦东锏
    原文地址: https://www.jianshu.com/p/1489fcbd2401
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞