1.配置:
1.1 AndroidManifest.xml中新增許可權和FileProvider:
--------------------------------------------------------------------------------------------------------------------
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
--------------------------------------------------------------------------------------------------------------------
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.fengzhi.wuyemanagement.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
複製程式碼
1.2 新建檔案(路徑:res\xml\file_paths.xml):
<paths>
<external-path path="." name="external_storage_root" />
</paths>
複製程式碼
1.3 (app的)build.gradle:
implementation "com.lzy.net:okgo:3.0.4"//okgo 網路請求
implementation 'com.google.code.gson:gson:2.8.2'//gson
implementation "org.permissionsdispatcher:permissionsdispatcher:4.3.1"//許可權
annotationProcessor "org.permissionsdispatcher:permissionsdispatcher-processor:4.3.1"//許可權
複製程式碼
2.這裡以點選按鈕進行更新為例:
2.1 核心程式碼:
private int version;
/* 更新進度條 */
private ProgressBar mProgress;
private AlertDialog mDownloadDialog;
--------------------------------------------------------------------------------------------------------------------
//點選按鈕,檢查許可權,,,檢查更新的方法
@NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.REQUEST_INSTALL_PACKAGES})
protected void checkUpdate() {
showLoadingDialog("檢測更新中...");
version = AppUpdateUtil.getAppVersionCode(this);//檢查當前版本號
// 呼叫方法,,,介面的具體實現,接收傳過來的引數,再調自己的方法,
requestAppUpdate(version, new DataRequestListener<UpdateAppBean>() {
@Override
public void success(UpdateAppBean data) {
// 返回的json,getStatus為0時,去下載apk檔案,這裡是下載apk檔案的方法
updateApp(data.getData().getApk_url());
}
@Override
public void fail(String msg) {
// 返回的json,getStatus為1時,提示:"已是最新版本!"
SToast(msg);
dismissLoadingDialog();
}
});
}
//檢查版本號,第一次請求(post),,,UpdateAppBean根據伺服器返回生成
private void requestAppUpdate(int version, final DataRequestListener<UpdateAppBean> listener) {
OkGo.<String>post(Const.HOST_URL + Const.UPDATEAPP).params("version", version).execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Gson gson = new Gson();
UpdateAppBean updateAppBean = gson.fromJson(response.body(), UpdateAppBean.class);
if (updateAppBean.getStatus() == 0) {
listener.success(updateAppBean);
} else {
listener.fail(updateAppBean.getMsg());
}
}
@Override
public void onError(Response<String> response) {
listener.fail("伺服器連線失敗");
dismissLoadingDialog();
}
});
}
//如果有新版本,提示有新的版本,然後下載apk檔案
private void updateApp(String apk_url) {
dismissLoadingDialog();
DialogUtils.getInstance().showDialog(this, "發現新的版本,是否下載更新?",
new DialogUtils.DialogListener() {
@Override
public void positiveButton() {
downloadApp(apk_url);
}
});
}
//下載apk檔案並跳轉(第二次請求,get)
private void downloadApp(String apk_url) {
OkGo.<File>get(apk_url).tag(this).execute(new FileCallback() {
@Override
public void onSuccess(Response<File> response) {
String filePath = response.body().getAbsolutePath();
Intent intent = IntentUtil.getInstallAppIntent(mContext, filePath);
// 測試過這裡必須用startactivity,不能用stratactivityforresult
mContext.startActivity(intent);
dismissLoadingDialog();
mDownloadDialog.dismiss();
mDownloadDialog=null;
}
@Override
public void downloadProgress(Progress progress) {
// showDownloadDialog();
// mProgress.setProgress((int) (progress.fraction * 100));
if (mDownloadDialog == null) {
// 構造軟體下載對話方塊
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("正在更新");
// 給下載對話方塊增加進度條
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.item_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
mDownloadDialog = builder.create();
mDownloadDialog.setCancelable(false);
mDownloadDialog.show();
}
mProgress.setProgress((int) (progress.fraction * 100));
}
});
}
複製程式碼
2.2 DataRequestListener:
public interface DataRequestListener<T> {
//請求成功
void success(T data);
//請求失敗
void fail(String msg);
}
複製程式碼
接下來是工具類,來自github,參考,github.com/vondear/RxT…
2.3 AppUpdateUtil:
/**
* 獲取App版本碼
*
* @param context 上下文
* @return App版本碼
*/
public static int getAppVersionCode(Context context) {
return getAppVersionCode(context, context.getPackageName());
}
複製程式碼
2.4 IntentUtil:
public class IntentUtil {
/**
* 獲取安裝App(支援7.0)的意圖
*
* @param context
* @param filePath
* @return
*/
public static Intent getInstallAppIntent(Context context, String filePath) {
//apk檔案的本地路徑
File apkfile = new File(filePath);
if (!apkfile.exists()) {
return null;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri contentUri = FileUtil.getUriForFile(context, apkfile);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
return intent;
}
複製程式碼
2.5 FileUtil:
/**
* 將檔案轉換成uri(支援7.0)
*
* @param mContext
* @param file
* @return
*/
public static Uri getUriForFile(Context mContext, File file) {
Uri fileUri = null;
if (Build.VERSION.SDK_INT >= 24) {
fileUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
} else {
fileUri = Uri.fromFile(file);
}
return fileUri;
}
複製程式碼
2.遇到的問題
9.0手機authorities配置出錯,導致無法安裝, 解決辦法:
1.專案中使用了Androidx,AndroidManifest.xml的配置中就必須使用androidx的fileprovider2.這裡的authorities與FileUtil.java中的要一樣,我就是字母P大寫了導致錯誤