Android版本更新升级所需
public class APKVersionCodeUtils {
/**
*获取本地版本号
*
*/
public static int getVersionCode(Context mContext) {
int versionCode = 0;
try {
//获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = mContext.getPackageManager().
getPackageInfo(mContext.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 获取版本号名称
*
* @param context 上下文
* @return
*/
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().
getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return verName;
}
}
public boolean isNeedUpdate(String version_service){
boolean isNeed = false;
try {
String version_current = getVerName();//获取当前本地版本
if (!TextUtils.isEmpty(version_service) && !TextUtils.isEmpty(version_current)) {
String[] service = version_service.split("\\.");
String[] current = version_current.split("\\.");
//这里因为服务器和本地版本号的格式一样,所以随便哪个的长度都可以使用
for (int i = 0; i < service.length; i++) {
int s = Integer.parseInt(service[i]);
int c = Integer.parseInt(current[i]);
if(c>s){
isNeed = false;
break;
}
if (c < s) {
isNeed = true;
break;
}
}
}
}catch (Exception e){
e.printStackTrace();
LogUtils.e("比较版本号时出错");
}
return isNeed;
}
public void loadNewVersionAlertDiaLog() { AlertDialog.Builder alert = new AlertDialog.Builder(ShowActivity.this); /** * 当后台的数据是分行处理时,接收数据后进行如下操作也能分行显示 String data = updateContent.replace("\\n", "\n");//updateContent为后台返回更新提示数据 */
alert.setTitle("说明"); alert.setMessage("发现新版本,是否立即更新?"); alert.setCancelable(false);//点击弹窗之外区域,弹框不消失 alert.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) { startUpload(upurl); //传入后台返回的apk下载地址 } }); alert.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alert.create(); alert.show(); }
private void startUpload(String downloadUrl){
progressDialog=new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("正在下载新版本。。。");
progressDialog.setCancelable(false);//不能手动取消下载进度对话框
final String fileSavePath=getSaveFilePath(downloadUrl);
HTTPCaller.getInstance().downloadFile(downloadUrl,fileSavePath,null,new ProgressUIListener(){
//下载开始
@Override
public void onUIProgressStart(long totalBytes) {
progressDialog.setMax((int)totalBytes);
progressDialog.show();
}
//更新进度
@Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
progressDialog.setProgress((int)numBytes);
}
//下载完成
@Override
public void onUIProgressFinish() {
Toast.makeText(MainActivity.this,"下载完成",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
openAPK(fileSavePath);
}
});
}
public static String getSaveFilePath(String fileUrl){
String fileName=fileUrl.substring(fileUrl.lastIndexOf("/")+1,fileUrl.length());//获取文件名称
String newFilePath= Environment.getExternalStorageDirectory() + "/Download/"+fileName;
return newFilePath;
}
4-1.初始化HTTPCaller类
项目build中导入使用包:implementation 'com.ansen.http:okhttpencapsulation:1.0.1'
然后于自定义的application中进行初始化
HttpConfig httpConfig = new HttpConfig();
httpConfig.setAgent(true);//有代理的情况能不能访问
httpConfig.setDebug(true);//是否debug模式 如果是debug模式打印log
httpConfig.setTagName("ansen");//打印log的tagname
//可以添加一些公共字段 每个接口都会带上
// httpConfig.addCommonField("pf", "android");
// httpConfig.addCommonField("version_code", "" + Utils.getVersionCode(getApplicationContext()));
//初始化HTTPCaller类
HTTPCaller.getInstance().setHttpConfig(httpConfig);
private void openAPK(String fileSavePath){
File file=new File(fileSavePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
// "cn.com.eyes3d.fileprovider"即是在清单文件中配置的authorities
// 通过FileProvider创建一个content类型的Uri
data = FileProvider.getUriForFile(this, "cn.com.eyes3d.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
} else {
// data = Uri.fromFile(file);
data= FileProvider.getUriForFile(this, "cn.com.eyes3d.fileprovider", file);
}
intent.setDataAndType(data, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后提示:完成 打开
startActivity(intent);
}
5-1.清单文件中添加provider
android:authorities="
android:exported="false"
android:grantUriPermissions="true">
android:resource="@xml/file_paths"/>
标红位置为包名,各位同时改成自己的就行
5-2.创建清单文件中的@xml/file_paths文件
题外话
/**
* 得到全局唯一UUID,即获取安卓唯一标识
*/
private String uuid;
public String getUUID(){
SharedPreferences mShare = getSharedPreferences("uuid",MODE_PRIVATE);
if(mShare != null){
uuid = mShare.getString("uuid", "");
}
if(TextUtils.isEmpty(uuid)){
uuid = UUID.randomUUID().toString();
mShare.edit().putString("uuid",uuid).commit();
}
return uuid;
}