apk更新前請注意:在每次更新apk只需要遞增versionCode即可,新版本的versionCode必須要比舊版本的大,versionName只是給用戶看的。
一.獲取本地apk版本信息(對應程序中build.gradle中的versionCode,versionName)

/* * 獲取當前程序的版本號 */ public static int getVersionCode(Context mContext) { int versionCode = 0; try { //獲取軟件版本號,對應AndroidManifest.xml下android:versionCode versionCode = mContext.getPackageManager(). getPackageInfo(mContext.getPackageName(), 0).versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } //獲取版本號名稱(對應versionName) public static String getVerName(Context context) { String verName = ""; try { verName = context.getPackageManager(). getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return verName; }
二.獲取服務器apk版本信息(說白了就是在服務器寫一個json或txt文件,里面標識着版本信息,鄙人才疏學淺,目前還不能直接獲取上傳至服務器apk內的版本信息)
1.添加網絡訪問權限

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!--下載文件讀寫權限--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.服務器上txt文件形式

#version.txt {"code":"2.0","update":"http://hnzldzkj.cn/static/apks/version.txt"}
3.訪問服務器txt文件並解析字段代碼(需在線程中調用)

private String getVersion() throws IOException, JSONException { URL url = new URL("http://hnzldzkj.cn/static/apks/version.txt"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setReadTimeout(8 * 1000); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String string; string = bufferedReader.readLine(); //對json數據進行解析 JSONObject jsonObject = new JSONObject(string); String strings = jsonObject.getString("code"); return strings; } //在線程中調用(a為全局變量 ps可設可不設(自己看情況,調用即可)) private void thread_start(){ new Thread(new Runnable() { @Override public void run() { try { a=getVersion(); }catch (Exception e){ } } }).start(); }
三.比較本地apk和服務器上apk的版本號(versionCode)

if(new_apkcode>getVersionCode(getContext())){ //如果新版本的versionCode大於舊版本的 showUpdataDialog(); }else { Toast.makeText(getActivity(),"當前為最新版本!",Toast.LENGTH_SHORT).show(); }
四.下載安裝apk
1.彈出對話框

protected void showUpdataDialog() { AlertDialog dialog = new AlertDialog.Builder(getContext()).create();//創建對話框 dialog.setIcon(R.mipmap.titles);//設置對話框icon dialog.setTitle("版本升級");//設置對話框標題 dialog.setMessage("軟件更新");//設置文字顯示內容 //分別設置三個button dialog.setButton(DialogInterface.BUTTON_POSITIVE,"確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { downLoadApk(); } }); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss();//關閉對話框 } }); dialog.show();//顯示對話框 }
2.設置進度條

protected void downLoadApk() { //進度條 final ProgressDialog pd; pd = new ProgressDialog(getContext()); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("正在下載更新"); pd.show(); new Thread(){ @Override public void run() { try { File file = getFileFromServer("http://hnzldzkj.cn/static/apks/采集大師.apk", pd); //安裝APK installApk(file); pd.dismiss(); //結束掉進度條對話框 } catch (Exception e) { } }}.start(); }
3.下載apk

public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{ //如果相等的話表示當前的sdcard掛載在手機上並且是可用的 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); //獲取到文件的大小 pd.setMax(conn.getContentLength()); InputStream is = conn.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(), "updata.apk"); FileOutputStream fos = new FileOutputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] buffer = new byte[1024]; int len ; int total=0; while((len =bis.read(buffer))!=-1){ fos.write(buffer, 0, len); total+= len; //獲取當前下載量 pd.setProgress(total); } fos.close(); bis.close(); is.close(); return file; } else{ return null; } }
4.安裝apk

protected void installApk(File file) { Intent intent = new Intent(); //執行動作 intent.setAction(Intent.ACTION_VIEW); //執行的數據類型 intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); }