前言
本文介紹安卓app全量更新
安卓app更新實(shí)現(xiàn)
一舷礼、實(shí)現(xiàn)更新步驟介紹
1、請求接口獲取到服務(wù)器版本和apk包的下載地址尉桩;
2筒占、獲取本地包版本;
3蜘犁、對比服務(wù)器版本和本地版本翰苫;
4、服務(wù)器版本大这橙,需要更新奏窑,下載apk包,使用手機(jī)已經(jīng)存在的第三方工具打開apk包屈扎;
5埃唯、安裝apk包。
二助隧、詳細(xì)代碼
1筑凫、在AndroidManifest.xml中
1)配置所需要的權(quán)限
<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" />
2)在application標(biāo)簽下添加
android:requestLegacyExternalStorage="true"
3)在application里添加
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.myupdateapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
2、創(chuàng)建xml文件夾并村,在xml文件夾下創(chuàng)建一個(gè)名為filepaths.xml的resouce文件
中的代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<external-path
name="external"
path="." />
<external-path
name="download"
path="" />
</paths>
</resources>
3巍实、UpdateManager里代碼
package com.example.myupdateapplication.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.example.myupdateapplication.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 更新管理
* 作者:created by fanHongJiao
*/
public class UpdateManager {
private Context mContext;
//是否是最新
private boolean isNew=false;
private boolean intercept=false;
private String apkUrl="https://file.shinedin.com/update_demo.apk";//線上apk地址
//保存APK的文件夾
private static String savePath;
//apk文件的絕對路徑
private static String saveFileName;
//下載線程
private Thread downLoadThread;
private int progress;//當(dāng)前進(jìn)度
TextView text;
//進(jìn)度條與通知UI刷新的handler和msg常量
private ProgressBar mProgress;
private static final int DOWN_UPDATTE=1;
private static final int DOWN_OVER=2;
private Handler mHandler=new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case DOWN_UPDATTE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
installApk2();
break;
default:
break;
}
}
};
public UpdateManager(Context context){
mContext=context;
//獲取存儲路徑,改存儲目錄在的
savePath=String.valueOf(mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS))+"/";
}
/**
* 獲取應(yīng)用的版本號
* @param context
* @return
*/
public static int getVersionCode(Context context){
PackageManager manager=context.getPackageManager();
int code=0;
PackageInfo info= null;
try {
info = manager.getPackageInfo(context.getPackageName(),0);
code=info.versionCode;
Log.e("code",code+"");
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return code;
}
public void checkVersion(){
int version=2;//服務(wù)器獲取到的版本號
if(UpdateManager.getVersionCode(mContext)<version){
//本地版本小于服務(wù)器版本哩牍,存在新版本
isNew=false;
}else{
isNew=true;
}
checkUpdateInfo();//判斷isNew,檢查是否需要更新操作
}
private void checkUpdateInfo() {
if(isNew){
Toast.makeText(mContext,"已是最新版本",Toast.LENGTH_SHORT).show();
return;
}else {
showUpdateDialog();
}
}
/**
* 顯示更新程序?qū)υ捒蚺锪剩┲鞒绦蛘{(diào)用
*/
private void showUpdateDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
builder.setTitle("軟件更新");
builder.setMessage("有最新的軟件包,是否下載膝昆!");
builder.setPositiveButton("下載", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
shoeDownloadDialog();
}
});
builder.setNegativeButton("以后再說", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
private void shoeDownloadDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
builder.setTitle("軟件更新");
LayoutInflater inflater=LayoutInflater.from(mContext);
View v=inflater.inflate(R.layout.progress,null);
mProgress=(ProgressBar)v.findViewById(R.id.progress);
builder.setView(v);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
intercept=true;//取消下載的標(biāo)識
}
});
builder.show();
downloadApk();
}
/**
*
* 從服務(wù)器下載apk包
*/
private void downloadApk() {
downLoadThread=new Thread(mdowApkRunable);//開啟一個(gè)新的線程下載apk
downLoadThread.start();
}
private Runnable mdowApkRunable=new Runnable() {
@Override
public void run() {
URL url;
try {
//對sd卡進(jìn)行狀態(tài)的判斷丸边,如果相等的話表示當(dāng)前的sdcard掛載在手機(jī)并且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//改目錄
url=new URL(apkUrl);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
int length=connection.getContentLength();
InputStream ins=connection.getInputStream();
//創(chuàng)建安裝包所在的前置文件夾
File file=new File(savePath);
if(!file.exists()){
file.mkdir();
}
//創(chuàng)建安裝包的文件,安裝包將下載入這個(gè)文件夾中
long time=System.currentTimeMillis();//當(dāng)前時(shí)間的毫秒數(shù)
saveFileName=savePath+time+"_apkupdate.apk";
File apkFile=new File(saveFileName);
//創(chuàng)建文件夾的輸入流
FileOutputStream fos=new FileOutputStream(apkFile);
int count=0;
byte[]buf=new byte[1024];
while (!intercept){//對取消下載的標(biāo)志進(jìn)行判斷荚孵,如果一直沒有被打斷即沒有點(diǎn)擊取消下載按鈕則繼續(xù)下載
int numread=ins.read(buf);//返回讀入的字節(jié)個(gè)數(shù)并將讀到的字節(jié)內(nèi)容放入buf中
count +=numread;
progress=(int)(((float)count/length)*100);//當(dāng)前進(jìn)度妹窖,用來更新progeessBar的進(jìn)度
//通知主線程更新下載進(jìn)度
mHandler.sendEmptyMessage(DOWN_UPDATTE);
if(numread<=0){
//下載完成通知安裝,自動安裝
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
//已經(jīng)全部讀入,不需要再讀入字節(jié)為-1的內(nèi)容
fos.write(buf,0,numread);
}
}else
return;
} catch (IOException e) {
Log.e("mdowApkRunable",e.getMessage());
e.printStackTrace();
}
}
};
private void installApk2(){
if(saveFileName!=null){
if(saveFileName.endsWith(".apk")){
if(Build.VERSION.SDK_INT>=24){//判斷版本是否在7.0以上
File file=new File(saveFileName);
String authority=mContext.getPackageName()+".fileprovider";//此處的值和AndroidManifes里的provider標(biāo)簽里的authorities值保持一致
Uri apkUri=FileProvider.getUriForFile(mContext,authority,file);
Intent install=new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.setDataAndType(apkUri,"application/vnd.android.package-archive");
mContext.startActivity(install);
}else {
Intent install=new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(saveFileName)),"application/vnd.android.package-archive");
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
mContext.startActivity(install);
}
}
}
}
}
4收叶、DowloadActivityDemon2里代碼
package com.example.myupdateapplication.utils;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.myupdateapplication.R;
import java.io.File;
public class DowloadActivityDemon2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dowload_demon2);
findViewById(R.id.btn_down).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UpdateManager updateManager=new UpdateManager(DowloadActivityDemon2.this);
updateManager.checkVersion();//檢查更新
}
});
}
}
完結(jié)骄呼。