Android使用DownloadMange進行版本更新(相容7.0)
阿新 • • 發佈:2019-01-25
1.簡單實現
直接上程式碼
package com.dyb.testcamerademo;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.File;
public class Main2Activity extends AppCompatActivity {
private Context mContext;
private DownloadManager mDownloadManager;
private long downloadId;
private boolean isForceUpdate = true;//是否強制升級
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mContext = this;
initVersionUpdate();
}
private void initVersionUpdate() {
checkUpdate();
}
/**
* 檢測軟體更新
*/
public void checkUpdate() {
if (isUpdate()) {
// 顯示提示對話方塊
showNoticeDialog();
} else {
Toast.makeText(mContext, "沒有新版", Toast.LENGTH_LONG).show();
}
}
/**
* 顯示軟體更新對話方塊
*/
private void showNoticeDialog() {
// 更新
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle("軟體更新")
.setMessage("檢測到新版本,立即更新嗎")
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(mContext, "正在通知欄下載中", Toast.LENGTH_SHORT).show();
// 顯示下載對話方塊
showDownloadDialog();
}
});
if (!isForceUpdate) {
dialog.setNegativeButton("下次再說", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
dialog.setCancelable(false);
dialog.show();
}
/**
* 顯示軟體下載對話方塊
*/
private void showDownloadDialog() {
//安裝包路徑 此處模擬為百度新聞APP地址
String downPath = "http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk";
//使用系統下載類
mDownloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse(downPath);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedOverRoaming(false);
//建立目錄下載
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "百度.apk");
// 把id儲存好,在接收者裡面要用
downloadId = mDownloadManager.enqueue(request);
//設定允許使用的網路型別,這裡是行動網路和wifi都可以
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
//機型適配
request.setMimeType("application/vnd.android.package-archive");
//通知欄顯示
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("測試APP");
request.setDescription("正在下載中...");
request.setVisibleInDownloadsUi(true);
mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
/**
* 判斷是否有更新,需要跟後臺產生資訊互動
*
* @return
*/
private boolean isUpdate() {
// 獲取當前軟體版本
int versionCode = getVersionCode(mContext);
// 呼叫方法獲取伺服器可用版本資訊,此處模擬為大於當前版本的定值
int serviceCode = 2;
// 版本判斷
if (serviceCode > versionCode) {
return true;
}
return false;
}
/**
* 獲取本地軟體版本號
*
* @param context
* @return
*/
private int getVersionCode(Context context) {
int versionCode = 0;
try {
// 獲取軟體版本號,對應AndroidManifest.xml下android:versionCode
versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkStatus();
}
};
/**
* 檢查下載狀態
*/
private void checkStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = mDownloadManager.query(query);
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:
installAPK();
break;
//下載失敗
case DownloadManager.STATUS_FAILED:
Toast.makeText(mContext, "下載失敗", Toast.LENGTH_SHORT).show();
break;
}
}
cursor.close();
}
/**
* 7.0相容
*/
private void installAPK() {
File apkFile =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "百度.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
mContext.startActivity(intent);
}
}
配置檔案AndroidManifest.xml程式碼:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dyb.testcamerademo">
<!-- sd卡寫許可權 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 網路 -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Main2Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.dyb.testcamerademo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
<activity android:name=".MainActivity">
</activity>
</application>
</manifest>
res包下新建xml包,新建的file_paths.xml程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--
name屬性的值可以隨便寫,別名
path屬性的值表示共享的具體位置,設定空就表示將整個SD卡進行共享
-->
<paths>
<external-path
name="camera_photos"
path=""/>
</paths>
</paths>