最近在做App版本更新这块的功能,以前也做过,为节省时间,提高开发效率,第一反应就是把之前的代码找出来直接用。三下五除二就搞定了,直接打个包给到测试!果然,一切都太顺利了,只见测试胸有成竹的走过来,说道:你这个版本更新有问题,没法安装!心里咯噔一下,怎么可能,我自己都测试OK的!立马反应过来,那估计是系统问题吧,后来确认,人家测试直接用的7.0的手机测试的。唉,好吧,那就改呗!
1.实现思路:
思路很简单,先判断是否需要版本更新,需要更新则启动一个服务去下载最新的apk,并注册一个广播监听下载进度,下载完成则安装apk。
2.代码实现:
(1)启动服务,若是6.0以上需要动态申请权限
Intent intent=new Intent(this, DownloadApkService.class);
intent.putExtra(DownloadApkService.DOWNLOAD_URL,"http://www.huiqu.co/public/download/apk/huiqu.apk");
startService(intent);
(2)在服务中下载
public int onStartCommand(Intent intent, int flags, int startId) {
String downLoadUrl = intent.getStringExtra(DOWNLOAD_URL);
mReceiver = new ApkInstallReceiver();
registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
if (DownLoadUtils.getInstance(this).canDownload()){
downloadApk(this,downLoadUrl,"app下载", appName);
}else {
DownLoadUtils.getInstance(this).skipToDownloadManager();
}
return Service.START_NOT_STICKY;
}
(
3
)下载完安装,这里是重点:
public class ApkInstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
installApk(context);
DownloadApkService.this.stopSelf();
}
}
/**
* 安装apk
*/
public void installApk(Context context) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DownloadApkService.DOWNLOADPATH + appName);
if (!file.exists()) {
Log.e(TAG, "file is not exists");
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "application/vnd.android.package-archive";
Uri downloadUri = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
downloadUri = Uri.fromFile(file);
} else {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
downloadUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(downloadUri, type);
context.startActivity(intent);
}
}
3.
查看AppUpdateDemo