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


private class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String data = http://www.kingceram.com/post/intent.getStringExtra(DownloadService.EXTENDED_DATA_STATUS);Log.i("test", data);long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);Toast.makeText(MainActivity.this, "编号:"+id+"的下载任务已经完成!", Toast.LENGTH_SHORT).show();intent = new Intent(Intent.ACTION_VIEW);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myApp.apk")),"application/vnd.android.package-archive");startActivity(intent);}}
最后取消注册广播:
protected void onDestroy() {super.onDestroy();cancel();LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);}
最后别忘了加上权限:

最终效果图如下:

Android中使用DownloadManager下载并安装apk

文章插图
放上.java的完整代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{MyReceiver receiver = new MyReceiver();private Button myselfButton;private String url = "http://172.30.18.222:8080/com.android36kr.app_16101017.apk";private DownloadDialog downloadDialog;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);regist();initView();}private void initView() {myselfButton = (Button)this.findViewById(R.id.myself_update);myselfButton.setOnClickListener(this);}private void regist() {IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);intentFilter.addCategory(Intent.CATEGORY_DEFAULT);LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);}public void download(){showDialog();Intent myserviceIntent = new Intent(MainActivity.this,MyDownloadService.class);myserviceIntent.setData(Uri.parse(url));startService(myserviceIntent);}@Overridepublic void onClick(View v) {switch(v.getId()){case R.id.myself_update:Intent serviceIntent = new Intent(MainActivity.this,DownloadService.class);serviceIntent.setData(Uri.parse(url));startService(serviceIntent);break;}}private class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String data = http://www.kingceram.com/post/intent.getStringExtra(DownloadService.EXTENDED_DATA_STATUS);Log.i("test", data);long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);Toast.makeText(MainActivity.this, "编号:"+id+"的下载任务已经完成!", Toast.LENGTH_SHORT).show();intent = new Intent(Intent.ACTION_VIEW);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myApp.apk")),"application/vnd.android.package-archive");startActivity(intent);}}protected void onDestroy() {super.onDestroy();cancel();LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);}}
实例实现强制更新:
Step 1:创建一个不可取消的(按back键不能取消,按弹窗外不可取消)
首先我们设置的 布局文件,.xml:

进度条显示下载进度,显示下载百分比 。
然后自定义一个,将布局文件设置进去,.java :