进入页面直接弹出版本对话框
MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialog(); } });//实现对画框
private void dialog() { if (status == 1) { new AlertDialog.Builder(this) .setIcon(R.mipmap.ic_launcher_round) .setTitle("发现新版本") .setMessage(msg) //升级按钮 .setPositiveButton("升级", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { downLoadApk(); //创建通知. createNotification(MainActivity.this); Toast.makeText(MainActivity.this, "开始升级", Toast.LENGTH_SHORT).show(); } }) //取消按钮 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "请及时升级到最新版本", Toast.LENGTH_SHORT).show(); } }).create().show(); } else { Toast.makeText(this, "当前版本是" + latest, Toast.LENGTH_SHORT).show(); } } //下载后文件保存的目录. private String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/"; private void downLoadApk() { //创建请求参数 RequestParams requestParams = new RequestParams(url); requestParams.setSaveFilePath(downLoadPath + "nihao"); x.http().request(HttpMethod.GET, requestParams, new org.xutils.common.Callback.ProgressCallback<File>() { @Override public void onSuccess(File file) { } @Override public void onError(Throwable throwable, boolean b) { } @Override public void onCancelled(CancelledException e) { } @Override public void onFinished() { } @Override public void onWaiting() { } @Override public void onStarted() { } //total:文件总大小,current,当前进度.isDownloading,是否正在下载. @Override public void onLoading(long total, long current, boolean isDownloading) { notifyNotification(current, total); if (total == current) {//若下载完成 mBuilder.setContentText("下载完成"); mNotifyManager.notify(10086, mBuilder.build()); //安装apk文件 installApk(MainActivity.this,new File(downLoadPath,"nihao")); } } }); } // 创建通知栏进度条 private void createNotification(Context context) { mNotifyManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(context); mBuilder.setSmallIcon(R.mipmap.ic_launcher_round); mBuilder.setContentTitle("版本更新"); mBuilder.setContentText("正在下载..."); mBuilder.setProgress(0, 0, false); Notification notification = mBuilder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; //参数1:通知id,参数:通知. mNotifyManager.notify(10086, notification); } /** * 更新通知栏进度条 */ private void notifyNotification(long percent, long length) { mBuilder.setProgress((int) length, (int) percent, false); mNotifyManager.notify(10086, mBuilder.build()); } /** * 安装apk * * @param context 上下文 * @param file APK文件 */ private void installApk(Context context, File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); }