Android app下载并安装
生活随笔
收集整理的這篇文章主要介紹了
Android app下载并安装
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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);
// 設(shè)置允許使用的網(wǎng)絡(luò)類型,這里是移動(dòng)網(wǎng)絡(luò)和wifi都可以
request.setAllowedNetworkTypes(request.NETWORK_MOBILE | request.NETWORK_WIFI);
//設(shè)置是否允許漫游
request.setAllowedOverRoaming(true);
//設(shè)置文件類型
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");
// 將下載請(qǐng)求放入隊(duì)列
downloadManager.enqueue(request);
}
2 設(shè)置接收廣播
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 注冊(cè)廣播(AndroidManifest.xml的receiver節(jié)點(diǎn))
<?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>
總結(jié)
以上是生活随笔為你收集整理的Android app下载并安装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS 8.1成功安装最新Node
- 下一篇: 自己写个网盘系列:② 看我不到700行代