1 下载功能
//下载apk
private void downloadApk(String apkUrl) throws PackageManager.NameNotFoundException {
Uri uri = Uri.parse(apkUrl);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
// 设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setAllowedNetworkTypes(request.NETWORK_MOBILE | request.NETWORK_WIFI);
//设置是否允许漫游
request.setAllowedOverRoaming(true);
//设置文件类型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkUrl));
request.setMimeType(mimeString);
//在通知栏中显示
request.setNotificationVisibility(request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("download...");
request.setVisibleInDownloadsUi(true);
//sdcard目录下的download文件夹
request.setDestinationInExternalPublicDir("/download", "SanjuScanApp_Android.apk");
// 将下载请求放入队列
downloadManager.enqueue(request);
}
2 设置接收广播
public class InstallReceiver extends BroadcastReceiver {
// 安装下载接收器
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
installApk(context);
}
}
// 安装Apk
private void installApk(Context context) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/SanjuScanApp_Android.apk";
i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3 注册广播(AndroidManifest.xml的receiver节点)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tyler.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
<activity
android:name=".LoginActivity"
</activity>
<receiver
android:name="com.example.tyler.HelperTool.InstallReceiver">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
</application>