之前一直在CSND發(fā)布文章,不過慢慢被簡書的排版布局所吸引,打算遷到這個平臺,這個是第一篇文章
下載并安裝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);
}
然后是監(jiān)聽下載完成的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();
}
};
在監(jiān)聽到下載的文件后,會調(diào)用stopSelf自動關(guān)閉該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);
}
}
很簡單的一篇文章,希望對大家有所幫助