Android sdk version 9以上就有DownManager
使用DownManager,我们可以很简便的在各个安卓机子上升级自家的应用
本例写了一个UpdataService实现后台下载新的APK到sdcard,并自动安装更新。
-
-
-
-
-
-
-
- public class UpdataService extends Service {
-
-
- DownloadManager manager;
-
-
- DownloadCompleteReceiver receiver;
-
-
- private void initDownManager() {
-
- manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
-
- receiver = new DownloadCompleteReceiver();
-
-
- DownloadManager.Request down = new DownloadManager.Request(
- Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));
-
-
- down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
- | DownloadManager.Request.NETWORK_WIFI);
-
-
- down.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
-
-
- down.setVisibleInDownloadsUi(true);
-
-
- down.setDestinationInExternalFilesDir(this,
- Environment.DIRECTORY_DOWNLOADS, "baidumusic.apk");
-
-
- manager.enqueue(down);
-
-
- registerReceiver(receiver, new IntentFilter(
- DownloadManager.ACTION_DOWNLOAD_COMPLETE));
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
-
-
- initDownManager();
-
- return super.onStartCommand(intent, flags, startId);
- }
-
- @Override
- public IBinder onBind(Intent intent) {
-
- return null;
- }
-
- @Override
- public void onDestroy() {
-
-
- if (receiver != null)
- unregisterReceiver(receiver);
-
- super.onDestroy();
- }
-
-
- class DownloadCompleteReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
-
-
- if (intent.getAction().equals(
- DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
-
-
- long downId = intent.getLongExtra(
- DownloadManager.EXTRA_DOWNLOAD_ID, -1);
-
-
- installAPK(manager.getUriForDownloadedFile(downId));
-
-
- UpdataService.this.stopSelf();
-
- }
- }
-
-
-
-
- private void installAPK(Uri apk) {
-
-
- Intent intents = new Intent();
-
- intents.setAction("android.intent.action.VIEW");
- intents.addCategory("android.intent.category.DEFAULT");
- intents.setType("application/vnd.android.package-archive");
- intents.setData(apk);
- intents.setDataAndType(apk,"application/vnd.android.package-archive");
- intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- android.os.Process.killProcess(android.os.Process.myPid());
-
-
- startActivity(intents);
-
- }
-
- }
- }
AndroidManifest.xml注册service
- <service
- android:name="com.example.test.UpdataService"
- android:enabled="true"
- >
- service>
添加调用DownManager的权限
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />