一、在 AndroidManifest.xml 中的準(zhǔn)備
- 進(jìn)行網(wǎng)絡(luò)請求,需要申請
<uses-permission android:name="android.permission.INTERNET" />權(quán)限 - 安裝 app ,需要申請
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />權(quán)限 - 讀取手機(jī)設(shè)備,需要申請
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />和<uses-permission android:name="android.permission.READ_PHONE_STATE" />權(quán)限 - 注冊一個 receiver 來監(jiān)聽下載完成和下載過程中點擊通知欄的事件
<receiver android:name=".reciever.DownLoadManagerReceiver">
<intent-filter>
<!-- 配置 點擊通知 和 下載完成 兩個 action -->
<action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
</intent-filter>
</receiver>
二、DownLoadManager 下載功能
/**
* 使用 DownloaderManager 下載
*
* @param downloadUrl
* @param fileName
* @param mimetype
*/
public static void downLoadUrl(String downloadUrl, String fileName, String mimetype) {
// 創(chuàng)建下載請求
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
/*
* 設(shè)置在通知欄是否顯示下載通知(下載進(jìn)度), 有 3 個值可選:
* VISIBILITY_VISIBLE: 下載過程中可見, 下載完后自動消失 (默認(rèn))
* VISIBILITY_VISIBLE_NOTIFY_COMPLETED: 下載過程中和下載完成后均可見
* VISIBILITY_HIDDEN: 始終不顯示通知
*/
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(true);
// 設(shè)置通知的標(biāo)題和描述
request.setTitle(fileName);
request.setDescription(fileName);
request.setMimeType(mimetype);
// 設(shè)置下載文件的保存位置
File saveFile = new File(Environment.getExternalStorageDirectory(), fileName);
request.setDestinationUri(Uri.fromFile(saveFile));
/*
* 2. 獲取下載管理器服務(wù)的實例, 添加下載任務(wù)
*/
DownloadManager manager = (DownloadManager) SystemUtil.getAppContext().getSystemService(Context.DOWNLOAD_SERVICE);
// 將下載請求加入下載隊列, 返回一個下載ID
long downloadId = manager.enqueue(request);
Log.d("Download", "downloadId=" + downloadId + "\tsaveFile=" + saveFile.getAbsolutePath());
}
三、下載完成監(jiān)聽
/**
* 檢查下載狀態(tài),是否下載成功
*/
public static void checkStatus(Context context) {
DownloadManager manager = getDownLoadManager();
DownloadManager.Query query = new DownloadManager.Query();
// 執(zhí)行查詢, 返回一個 Cursor (相當(dāng)于查詢數(shù)據(jù)庫)
Cursor cursor = manager.query(query);
if (!cursor.moveToFirst()) {
cursor.close();
}
int id = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
//通過下載的id查找
query.setFilterById(id);
// 獲取下載好的 apk 路徑
String localFilename = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
} else {
localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
}
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
//下載暫停
break;
case DownloadManager.STATUS_PENDING:
//下載延遲
break;
case DownloadManager.STATUS_RUNNING:
//正在下載
break;
case DownloadManager.STATUS_SUCCESSFUL:
Log.d("Download", "localFilename:" + localFilename);
//下載完成安裝APK
installApp(context, localFilename);
cursor.close();
break;
case DownloadManager.STATUS_FAILED:
//下載失敗
cursor.close();
break;
default:
break;
}
}
}
自定義DownLoadManagerReceiver,實現(xiàn)監(jiān)聽
public class DownLoadManagerReceiver extends BootBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Log.d("Download", "用戶點擊了通知");
// 點擊下載進(jìn)度通知時, 對應(yīng)的下載ID以數(shù)組的方式傳遞
long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
Log.d("Download", "ids: " + Arrays.toString(ids));
long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
Log.d("Download", "id: " + completeDownloadId);
//這里可以做暫停下載功能
} else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Log.d("Download", "下載完成");
DownLoadUtil.checkStatus(context);
}
}
}
四、調(diào)起apk安裝
/**
* 安裝apk
*
* @param context
* @param path
*/
private static void installApp(Context context, String path) {
Log.d("Download", "installApp: StorageState = " + Environment.getExternalStorageState());
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Uri.parse(path).getPath()去除 file://
File targetFile = new File(Uri.parse(path).getPath());
Log.i("Download", "targetFile: " + targetFile.getPath() + "\ttargetFile = " + targetFile.getAbsolutePath() + "\ttargetFile 是否存在:" + targetFile.exists());
if (targetFile.exists()) {//先判斷文件是否已存在
Log.i("Download", "targetFile: ---" + targetFile.getPath());
//1. 創(chuàng)建 Intent 并設(shè)置 action
Intent intent = new Intent(Intent.ACTION_VIEW);
//2. 設(shè)置 category
intent.addCategory(Intent.CATEGORY_DEFAULT);
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", targetFile);
//添加 flag ,不記得在哪里看到的,說是解決:有些機(jī)器上不能成功跳轉(zhuǎn)的問題
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加這一句表示對目標(biāo)應(yīng)用臨時授權(quán)該Uri所代表的文件
//3. 設(shè)置 data 和 type
intent.setDataAndType(uri, "application/vnd.android.package-archive");
//3. 設(shè)置 data 和 type (效果和上面一樣)
//intent.setDataAndType(Uri.fromFile(targetFile),"application/vnd.android.package-archive");
//intent.setDataAndType(Uri.parse("file://" + targetFile.getPath()),"application/vnd.android.package-archive");
//4. 啟動 activity
context.startActivity(intent);
}
}
}
在 AndroidManifest 中 聲明 provider:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path"
tools:replace="android:resource"/>
</provider>
file_path.xml文件在 res 的 xml 目錄下:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
這里為什么要申明 FileProvider ?[參考鏈接]
原因在于使用file://Uri會有一些風(fēng)險,比如:
- 文件是私有的,接收file://Uri的app無法訪問該文件。
- 在Android6.0之后引入運行時權(quán)限,如果接收file://Uri的app沒有申請READ_EXTERNAL_STORAGE權(quán)限,在讀取文件時會引發(fā)崩潰。
因此,google提供了FileProvider 類,使用它可以生成content://Uri來替代file://Uri,所以要在應(yīng)用間共享文件,應(yīng)發(fā)送一項 content:// URI,并授予 URI 臨時訪問權(quán)限。
FileProvider是android support v4包提供的,是ContentProvider的子類,便于將自己app的數(shù)據(jù)提供給其他app訪問。
在app開發(fā)過程中需要用到FileProvider的主要有
- 相機(jī)拍照以及圖片裁剪
- 調(diào)用系統(tǒng)應(yīng)用安裝器安裝apk(應(yīng)用升級)
- 分享文件
有時候廣告第三方也會引入 FileProvider,這就會導(dǎo)致 FileProvider 重復(fù),只需要重新建立一個空類繼承 FileProvider 里面什么都不用寫,在 AndroidManifest 中申明自定義的 FileProvider 即可
至此從下載 Apk 到下載完成后自動調(diào)起安裝就完成了
這里有個小 tip:
可以通過下載的路徑,獲取到 ApkInfo,得到對應(yīng)的包信息