Android中使用DownloadManager下载并安装apk( 四 )


Step 3:在里中更新下载状态(回调主线程中,更新UI)
在主线程中通过获取,并回调方法处理信息,更新UI,.java:
Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case DownloadManager.STATUS_SUCCESSFUL:downloadDialog.setProgress(100);canceledDialog();Toast.makeText(MainActivity.this, "下载任务已经完成!", Toast.LENGTH_SHORT).show();break;case DownloadManager.STATUS_RUNNING://int progress = (int) msg.obj;downloadDialog.setProgress((int) msg.obj);//canceledDialog();break;case DownloadManager.STATUS_FAILED:canceledDialog();break;case DownloadManager.STATUS_PENDING:showDialog();break;}}};
Step 4:下载完成后进行安装(静态注册广播接收器,实现安装功能)
.xml:

接受广播并自行安装应用,.java:
public class InstallApkBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {install(context);}private void install(Context context) {Intent installintent = new Intent();installintent.setAction(Intent.ACTION_VIEW);// 在Boradcast中启动活动需要添加Intent.FLAG_ACTIVITY_NEW_TASKinstallintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);installintent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myApp.apk")),"application/vnd.android.package-archive");//存储位置为Android/data/包名/file/Download文件夹context.startActivity(installintent);}}
最后别忘了加上权限:

最终效果为:
【Android中使用DownloadManager下载并安装apk】

Android中使用DownloadManager下载并安装apk

文章插图
这里放上的完整代码:
.java:
public class MainActivity extends AppCompatActivity {private Button force_button;private DownloadDialog downloadDialog;private DownloadManager mDownloadManager;private String url = "http://172.30.18.222:8080/lanota.apk";Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case DownloadManager.STATUS_SUCCESSFUL:downloadDialog.setProgress(100);canceledDialog();Toast.makeText(MainActivity.this, "下载任务已经完成!", Toast.LENGTH_SHORT).show();break;case DownloadManager.STATUS_RUNNING://int progress = (int) msg.obj;downloadDialog.setProgress((int) msg.obj);//canceledDialog();break;case DownloadManager.STATUS_FAILED:canceledDialog();break;case DownloadManager.STATUS_PENDING:showDialog();break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);force_button = (Button)this.findViewById(R.id.force_button);force_button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {download();}});}private void download() {showDialog();//最好是用单线程池,或者intentService取代new Thread(new DownLoadRunnable(this,url, handler)).start();}private void showDialog() {if(downloadDialog==null){downloadDialog = new DownloadDialog(this);}if(!downloadDialog.isShowing()){downloadDialog.show();}}private void canceledDialog() {if(downloadDialog!=null&&downloadDialog.isShowing()){downloadDialog.dismiss();}}}