Android 从服务器下载最新APP并更新当前
首先获取当前最新的APP版本号
public long getCurrentVersionCode(){
long CurrentVersionCode = 0;
try {
PackageInfo packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);
CurrentVersionCode = packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
}
return CurrentVersionCode;
};
当前版本号跟获取的最新版本号对比 同时判断是否是强制更新,强制更新取消则关闭应用
传入最新apk的对应下载地址
public void downloadApl(final String apkurl){
Toast.makeText(context, "开始下载"+apkurl, Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(inflate);
builder.create();
builder.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(apkurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
final int contentLength = connection.getContentLength();//文件大小
InputStream inputStream = connection.getInputStream();
File file = new File(saveFilePath);
if(!file.exists()){
file.mkdir();
}
String apkFile = saveFileName;
File apkfile = new File(apkFile);
FileOutputStream fileOutputStream = new FileOutputStream(apkFile);
int count = 0;
int lenth = 0;
byte[] bytes = new byte[512];
while( (lenth = inputStream.read(bytes))!=-1){
count+=lenth;
fileOutputStream.write(bytes,0,lenth);
Message message = new Message();
message.arg1 = count;
message.arg2 = contentLength;
message.what = 2;
handler.sendMessage(message);
fileOutputStream.flush();
}
handler.sendEmptyMessage(1);
fileOutputStream.close();
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
将下载好的apk安装到本机
//安装APK
public void installApl(){
File file = new File(saveFilePath,"apkName.apk");
if(!file.exists()){
return;
}
Intent intent=new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
String string = "com.example.project_class6_sc"+".fileprovider";
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(context.getApplicationContext(), string, file);
intent.setDataAndType(uri,"application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.parse("file://"+file.toString()),"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}