Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android APK 自動檢測升級功能實作

編輯:關於 Android 程式設計

實作 APK 自動更新,大致分為三個步驟:取得本地版本、取得伺服器版本、比對後下載更新。

一、取得本地 APK 版本

/**
 * 獲取本地軟件版本
 */
public static int getLocalVersion(Context ctx){
 int localVersion = 0;
 try {
 PackageInfo packageInfo = ctx.getApplicationContext()
 .getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
 localVersion = packageInfo.versionCode;
 Log.d("TAG", "本軟件的版本。。"+localVersion);
 } catch (NameNotFoundException e) {
 e.printStackTrace();
 }
 return localVersion;
}

二、取得伺服器版本並比對

取得伺服器版本的方式有很多種,可自由發揮。取得後與本地 APK 版本進行比較,若本地版本低於伺服器版本,就進行更新。以下以非同步下載搭配通知欄顯示進度為例(僅供參考):

/**
 * 用於更新app版本
 *
 * @param ctx 上下文對象
 * @param url 更新版本的地址
 */
private static PendingIntent pendingIntent;
public static void UpdateVersion(final Context ctx, String url) {
 createNotification(ctx); // 創建文件,讀取app_name
 createFile(ctx.getResources().getString(R.string.app_name));
 new AsyncTask() {
 @Override protected String doInBackground(String... params) {
 int down_step = 1;// 提示step
 int totalSize;// 文件總大小
 int downloadCount = 0;// 已經下載好的大小
 int updateCount = 0;// 已經上傳的文件大小
 InputStream inputStream;
 OutputStream outputStream;
 URL url;
 HttpURLConnection httpURLConnection = null;
 try {
 url = new URL(params[0]);
 httpURLConnection = (HttpURLConnection) url.openConnection();
 httpURLConnection.setConnectTimeout(TIMEOUT);
 httpURLConnection.setReadTimeout(TIMEOUT);
 totalSize = httpURLConnection.getContentLength();
 if (httpURLConnection.getResponseCode() == 404) {
 throw new Exception("fail!");
 }
 inputStream = httpURLConnection.getInputStream();
 outputStream = new FileOutputStream(updateFile, false);// 文件存在則覆蓋掉
 byte buffer[] = new byte[1024];
 int readsize = 0;
 while ((readsize = inputStream.read(buffer)) != -1) {
 outputStream.write(buffer, 0, readsize);
 downloadCount += readsize;// 時時獲取下載到的大小
 if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
 updateCount += down_step;
 builder = new Notification.Builder(ctx)
 .setSmallIcon(R.drawable.logo)
 .setContentText("正在下載(" + updateCount + "%)...")
 .setProgress(100, updateCount, false);
 manager.notify(8, builder.build());
 }
 }
 if (httpURLConnection != null) {
 httpURLConnection.disconnect();
 }
 inputStream.close();
 outputStream.close();
 } catch (MalformedURLException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }
 @Override protected void onPostExecute(String result) {
 // 下載完成,點擊安裝
 System.out.println("updateFile.." + updateFile);
 Uri uri = Uri.fromFile(updateFile);
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(uri, "application/vnd.android.package-archive");
 pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);
 builder = new Notification.Builder(ctx)
 .setSmallIcon(R.drawable.logo)
 .setContentIntent(pendingIntent)
 .setContentTitle("apk下載更新")
 .setContentText("下載成功,請點擊安裝")
 .setProgress(100, 100, false);
 manager.notify(8, builder.build());
 }
 }.execute(url);
}
private static void createNotification(Context ctx) {
 // 最普通的通知欄
 manager = (NotificationManager) ctx.getSystemService(ctx.NOTIFICATION_SERVICE);
 builder = new Notification.Builder(ctx).setSmallIcon(R.drawable.logo)
 .setContentTitle("apk下載更新").setContentText("准備下載...")
 .setProgress(100, 0, false);
 manager.notify(8, builder.build());
}

下載完成後,使用者即可點擊通知進行安裝。

特別提醒:若你的 APK 已經簽名,而手機上現有的 APK 未經簽名,安裝時會出現「簽名不同的套件衝突」而無法安裝,這種情況只能先卸載未簽名的 APK 後再重新安裝。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved