注意 file_paths和 android:authorities="${applicationId}.fileprovider"
//APP更新
private final String TAG = "Jason";
private File file;
private List<AppVerBean> eduList = null; //接收网app版本
private List<CharSequence> leduList = null;
String targetVersion = ""; //todo 实际目标版本号应向平台查询---
String locVersion = ""; //todo 本地--
String downloadUrl = ""; //todo 实际下载地址应向平台查询
String yunmdownload_path = "";
private String downLoadPath ="";
private AlertDialog.Builder updataDialog;
private AlertDialog.Builder installDialog;
private ProgressDialog progressDialog;
private String newApkName = "app-debug.apk";
--------------------
//查询app更新版本 File fileEx = this.getExternalFilesDir(null); downLoadPath = fileEx.getAbsolutePath() + "/client"; locVersion =getVersionName();//查询本地版本 InternetSeverAppVer_json();//app版本查询
----------------
//APP更新+++++++++++++++++++++++++++++
// //升级star 注意 file_paths和 android:authorities="${applicationId}.fileprovider"
//新版本检测
//获取软件版本号
private String getVersionName() {
String versionName = "";
try {
versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
/**
* 版本号比较
*
* @param version1
* @param version2
* @return
*/
public static int compareVersion(String version1, String version2) {
if (version1.equals(version2)) {
return 0;
}
String[] version1Array = version1.split("\\.");
String[] version2Array = version2.split("\\.");
Log.d("HomePageActivity", "version1Array=="+version1Array.length);
Log.d("HomePageActivity", "version2Array=="+version2Array.length);
int index = 0;
// 获取最小长度值
int minLen = Math.min(version1Array.length, version2Array.length);
int diff = 0;
// 循环判断每位的大小
Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
while (index < minLen
&& (diff = Integer.parseInt(version1Array[index])
- Integer.parseInt(version2Array[index])) == 0) {
index++;
}
if (diff == 0) {
// 如果位数不一致,比较多余位数
for (int i = index; i < version1Array.length; i++) {
if (Integer.parseInt(version1Array[i]) > 0) {
return 1;
}
}
for (int i = index; i < version2Array.length; i++) {
if (Integer.parseInt(version2Array[i]) > 0) {
return -1;
}
}
return 0;
} else {
return diff > 0 ? 1 : -1;
}
}
//取网络版本
private void InternetSeverAppVer_json() {
OkHttpClient client = new OkHttpClient();
String urlt = "http://app.59cg.com//api//TlqlappUpdate//" +"1";//写自己的服务器url ?pass=0
final Request request = new Request.Builder()
.url(urlt)
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e);
Looper.prepare();
Toast.makeText(getApplication(), "网络异常,请稍后再试!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String datatV = response.body().string();//得到实体
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
Gson gson = new Gson();
String str = datatV.substring(1, datatV.length() - 1).replaceAll("\\\\", "");
//json转换为list
if(str.length()<1)
{
Toast.makeText(getApplication(), "没有数据", Toast.LENGTH_SHORT).show();
}
else {
eduList = gson.fromJson(str, new TypeToken<List<AppVerBean>>(){}.getType());
}
//加强for循环遍历JsonArray
String id = "";
leduList = new ArrayList<CharSequence>();//不知道为什么要转换
if (!eduList.isEmpty()) {
for(int i = 0; i < eduList.size() ; i++)
{
AppVerBean p = eduList.get(i);
downloadUrl=p.getUrl();
yunmdownload_path=p.getUrl();
targetVersion=p.getVersionCode();
//判断版本号的大小,大于网络上的版本号不提示更新
// int verflag = compareVersiont(locVersion, targetVersion);
int verflagt = compareVersion(locVersion, targetVersion);
if (verflagt == -1)
{
showTip(getApplication());
}
// leduList.add(eduList.get(i).getVersionCode());
}
}
}
});
}
//升级弹窗
private void showTip(Context context) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//写入本地数据
showUpdataDialog("im");
}
});
}
/**
* 版本更新提示框
*/
public void showUpdataDialog(String content) {
updataDialog = new AlertDialog.Builder(MainActivity.this);
updataDialog.setTitle("检查更新");
updataDialog.setMessage( content);
updataDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
updataDialog.setPositiveButton("确定更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createProgress(MainActivity.this);
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
downloadApk();
Looper.loop();//增加部分
}
}).start();
}
});
updataDialog.show( );
}
/**
* 强制更新时显示在屏幕的进度条
*/
private void createProgress(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.setMessage("正在下载...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
/**
* 下载APK
*/
private void downloadApk() {
try {
final long startTime = System.currentTimeMillis();
Log.i("DOWNLOAD", "startTime=" + startTime);
//获取文件名
URL myURL = new URL(yunmdownload_path);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int fileSize = conn.getContentLength();//根据响应获取文件大小
Log.i("DOWNLOAD", "总大小="+fileSize);
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File file1 = new File(downLoadPath);
if (!file1.exists()) {
file1.mkdirs();
}
//把数据存入路径+文件名
FileOutputStream fos = new FileOutputStream(downLoadPath + "/" + newApkName);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
do {
//循环读取
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
Log.i("DOWNLOAD", "downLoadFileSize="+downLoadFileSize);
Log.i("DOWNLOAD", "fileSize="+fileSize);
Log.i("DOWNLOAD", "download downLoadFileSize="+(int)((float)downLoadFileSize*100/fileSize));
progressDialog.setProgress((int)((float)downLoadFileSize*100/fileSize));
//更新进度条
} while (true);
delOldApk();
progressDialog.dismiss();
showInstallDialog("下载完成,是否安装?");
Log.i("DOWNLOAD", "download success");
Log.i("DOWNLOAD", "totalTime=" + (System.currentTimeMillis() - startTime));
is.close();
} catch (Exception ex) {
Log.e("DOWNLOAD", "111111 error: " + ex.getMessage(), ex);
progressDialog.cancel();
try{
AlertDialog.Builder adBd=new AlertDialog.Builder(MainActivity.this);
adBd.setTitle("下载错误");
adBd.setMessage("检查网络或者服务器!");
adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
adBd.show();
}
catch (Exception e){
Log.e("DOWNLOAD_EEE", "111111 error: " + ex.getMessage(), ex);
}
}
}
/**
* 弹出安装Dialog
*/
private void showInstallDialog(String content){
installDialog = new AlertDialog.Builder(MainActivity.this);
installDialog.setMessage( content);
installDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
installDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
File fileAPK = new File(downLoadPath, newApkName);
installappApk(fileAPK);
}
});
installDialog.show();
}
/**
* 删除旧的apk
*/
private void delOldApk(){
// File fileAPK = new File(downLoadPath, oldApkName);
//if(fileAPK.exists()){
// fileAPK.delete();
// }
}
/**
* 安装apk
*/
private void installApk(Context context, File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
startActivity(intent);
}
private void installappApk(File file) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
}
------------
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true" tools:replace="android:authorities"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" tools:replace="android:resource" /> </provider>
---------------
<?xml version="1.0" encoding="utf-8"?> <paths > <external-path name="external_path" path="." /> <external-path name="my_images" path="images/" /> <files-path name="name" path="path" /> <cache-path name="name" path="path" /> <external-path name="name" path="client" /> <external-path name="download" path="Download" /> <external-files-path name="name" path="path" /> <external-cache-path name="name" path="path" /> </paths>