安卓新版本升級,並自動安裝apk
阿新 • • 發佈:2019-01-29
記得新增intenet許可權,和sdcard的讀寫許可權
public class MainActivity extends AppCompatActivity { private String url = "具體下載新的apk的路勁"; private int versionCode; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); x.view().inject(this); //得到當前的版本號,由於沒有釋出,所以無法得到新版本,暫時可以加頁可以不加 try { versionCode = getPackageManager().getPackageInfo(getPackageName(), 0)
.versionCode; } catch (Exception e) { e.printStackTrace(); }
//發現新版本你的時候彈出對話方塊 AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("發現新版本是否升級?"); builder.setPositiveButton("升級", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { initData(); } }); builder.setNegativeButton("取消", null); builder.create().show(); } private voidinitData() { //設定檔案下載的位置和檔名字 String path = Environment.getExternalStorageDirectory().
getPath() + "/app.apk"; RequestParams params = new RequestParams(url); //設定程式不重新給下載的檔案重新設定名字 params.setAutoRename(false); //設定斷點續傳 params.setAutoResume(true); //設定下載儲存的路徑 params.setSaveFilePath(path); x.http().get(params, new Callback.ProgressCallback<File>() { @Override public void onSuccess(File result) { Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//可加可不加
//第一個引數是你下載的檔案,第二個是固定內容,可直接複製 intent.setDataAndType(Uri.fromFile(result),
"application/vnd.android.package-archive"); startActivity(intent); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { if (dialog != null & dialog.getProgress() >= 100 &&
dialog.isShowing()) { dialog.dismiss(); Toast.makeText(MainActivity.this, "升級完成",
Toast.LENGTH_SHORT).show(); } } @Override public void onWaiting() { } @Override public void onStarted() { //初始化ProgressDiaLog initProgressDiaLog(); } @Override public void onLoading(long total, long current, boolean isDownloading)
{ //判斷是否是在下載中,可加也可不加 if (isDownloading) { //算出來當前進度 int progress = (int) (current * 100 / total ); //把進度設定給progressBar dialog.setProgress(progress); } } }); } //建立進度條 private void initProgressDiaLog() { dialog = new ProgressDialog(this); dialog.setTitle("正在下載中..."); dialog.setProgress(0); dialog.setCancelable(false); //設定不可點選介面之外的區域讓對話方塊消失 //設定進度條的樣式 dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.show(); } }