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);
}

}

很簡單的一篇文章,希望對大家有所幫助

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容