歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 自動檢測版本升級

Android 自動檢測版本升級

日期:2017/3/1 10:10:57   编辑:Linux編程

在我們APP的開發中,往往都會遇到版本的升級,因為不可能有任何一個應用做的完美無缺,所以版本升級對APP應用來說是不可缺少的一部分.像新浪微博等一些應用軟件,三天兩頭提醒我升級.不過這樣也很正常,就像Android 升級一樣,為了給用戶提供更方便更人性化的操作.說下具體實現吧,不過我是參考別人的。不管對你們有沒有幫助,總之對我有幫助啊,如果日後用到就直接copy了.哈哈,不扯了。

首先看一個文件manifest文件.

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.jj.upgrade"
  3. android:versionCode="1"
  4. android:versionName="1.0" >

我們可以很清楚的看到versionCode和versionName,我們一般用versionCode來實現,

實現原理很簡單:服務器端有個serverVersion,我們本地有個localVersion.服務器端serverVersion>localVersion,這個時候我們就需要進行升級版本.原理大致就是這樣。具體實現請看下面.

  1. package com.jj.upgrade;
  2. import com.jj.Service.UpdateService;
  3. import android.app.AlertDialog;
  4. import android.app.Application;
  5. import android.content.DialogInterface;
  6. import android.content.Intent;
  7. import android.content.pm.PackageInfo;
  8. import android.content.pm.PackageManager.NameNotFoundException;
  9. /***
  10. * MyApplication
  11. *
  12. * @author zhangjia
  13. *
  14. */
  15. public class MyApplication extends Application {
  16. public static int localVersion = 0;// 本地安裝版本
  17. public static int serverVersion = 2;// 服務器版本
  18. public static String downloadDir = "jj/";// 安裝目錄
  19. @Override
  20. public void onCreate() {
  21. super.onCreate();
  22. try {
  23. PackageInfo packageInfo = getApplicationContext()
  24. .getPackageManager().getPackageInfo(getPackageName(), 0);
  25. localVersion = packageInfo.versionCode;
  26. } catch (NameNotFoundException e) {
  27. e.printStackTrace();
  28. }
  29. /***
  30. * 在這裡寫一個方法用於請求獲取服務器端的serverVersion.
  31. */
  32. }
  33. }

我們一般把全局的東西放到application裡面

  1. public class MainActivity extends Activity {
  2. private MyApplication myApplication;
  3. @Override
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.main);
  7. checkVersion();
  8. }
  9. /***
  10. * 檢查是否更新版本
  11. */
  12. public void checkVersion() {
  13. myApplication = (MyApplication) getApplication();
  14. if (myApplication.localVersion < myApplication.serverVersion) {
  15. // 發現新版本,提示用戶更新
  16. AlertDialog.Builder alert = new AlertDialog.Builder(this);
  17. alert.setTitle("軟件升級")
  18. .setMessage("發現新版本,建議立即更新使用.")
  19. .setPositiveButton("更新",
  20. new DialogInterface.OnClickListener() {
  21. public void onClick(DialogInterface dialog,
  22. int which) {
  23. Intent updateIntent = new Intent(
  24. MainActivity.this,
  25. UpdateService.class);
  26. updateIntent.putExtra(
  27. "app_name",
  28. getResources().getString(
  29. R.string.app_name));
  30. startService(updateIntent);
  31. }
  32. })
  33. .setNegativeButton("取消",
  34. new DialogInterface.OnClickListener() {
  35. public void onClick(DialogInterface dialog,
  36. int which) {
  37. dialog.dismiss();
  38. }
  39. });
  40. alert.create().show();
  41. }
  42. }
  43. }

我們在運行應用的時候要checkVersion();進行檢查版本是否要進行升級.

最主要的是UpdateService服務類,

  1. @Override
  2. public int onStartCommand(Intent intent, int flags, int startId) {
  3. app_name = intent.getStringExtra("app_name");
  4. // 創建文件
  5. FileUtil.createFile(app_name);// 創建文件
  6. createNotification();// 首次創建
  7. createThread();// 線程下載
  8. return super.onStartCommand(intent, flags, startId);
  9. }

創建路徑及文件,這裡就不介紹了,不明白了下載源碼看.

首先我們先 看createNotification().這個方法:

  1. /***
  2. * 創建通知欄
  3. */
  4. RemoteViews contentView;
  5. public void createNotification() {
  6. notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  7. notification = new Notification();
  8. notification.icon = R.drawable.ic_launcher;// 這個圖標必須要設置,不然下面那個RemoteViews不起作用.
  9. // 這個參數是通知提示閃出來的值.
  10. notification.tickerText = "開始下載";
  11. //
  12. // updateIntent = new Intent(this, MainActivity.class);
  13. // pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
  14. //
  15. // // 這裡面的參數是通知欄view顯示的內容
  16. // notification.setLatestEventInfo(this, app_name, "下載:0%",
  17. // pendingIntent);
  18. //
  19. // notificationManager.notify(notification_id, notification);
  20. /***
  21. * 在這裡我們用自定的view來顯示Notification
  22. */
  23. contentView = new RemoteViews(getPackageName(),
  24. R.layout.notification_item);
  25. contentView.setTextViewText(R.id.notificationTitle, "正在下載");
  26. contentView.setTextViewText(R.id.notificationPercent, "0%");
  27. contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
  28. notification.contentView = contentView;
  29. updateIntent = new Intent(this, MainActivity.class);
  30. updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  31. pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
  32. notification.contentIntent = pendingIntent;
  33. notificationManager.notify(notification_id, notification);
  34. }

上面實現的也不難理解.(主要是初始化Notification,用於提醒用戶開始下載)

接著我們要看createThread方法

  1. /***
  2. * 開線程下載
  3. */
  4. public void createThread() {
  5. /***
  6. * 更新UI
  7. */
  8. final Handler handler = new Handler() {
  9. @Override
  10. public void handleMessage(Message msg) {
  11. switch (msg.what) {
  12. case DOWN_OK:
  13. // 下載完成,點擊安裝
  14. Uri uri = Uri.fromFile(FileUtil.updateFile);
  15. Intent intent = new Intent(Intent.ACTION_VIEW);
  16. intent.setDataAndType(uri,
  17. "application/vnd.android.package-archive");
  18. pendingIntent = PendingIntent.getActivity(
  19. UpdateService.this, 0, intent, 0);
  20. notification.setLatestEventInfo(UpdateService.this,
  21. app_name, "下載成功,點擊安裝", pendingIntent);
  22. notificationManager.notify(notification_id, notification);
  23. stopSelf();
  24. break;
  25. case DOWN_ERROR:
  26. notification.setLatestEventInfo(UpdateService.this,
  27. app_name, "下載失敗", pendingIntent);
  28. break;
  29. default:
  30. stopSelf();
  31. break;
  32. }
  33. }
  34. };
  35. final Message message = new Message();
  36. new Thread(new Runnable() {
  37. @Override
  38. public void run() {
  39. try {
  40. long downloadSize = downloadUpdateFile(down_url,
  41. FileUtil.updateFile.toString());
  42. if (downloadSize > 0) {
  43. // 下載成功
  44. message.what = DOWN_OK;
  45. handler.sendMessage(message);
  46. }
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. message.what = DOWN_ERROR;
  50. handler.sendMessage(message);
  51. }
  52. }
  53. }).start();
  54. }

這個方法有點小多,不過我想大家都看的明白,我在這裡簡單說名一下:首先我們創建一個handler用於檢測最後下載ok還是not ok.

下面我們開啟了線程進行下載數據。

我們接著看downloadUpdateFile這個方法:

  1. /***
  2. * 下載文件
  3. *
  4. * @return
  5. * @throws MalformedURLException
  6. */
  7. public long downloadUpdateFile(String down_url, String file)
  8. throws Exception {
  9. int down_step = 5;// 提示step
  10. int totalSize;// 文件總大小
  11. int downloadCount = 0;// 已經下載好的大小
  12. int updateCount = 0;// 已經上傳的文件大小
  13. InputStream inputStream;
  14. OutputStream outputStream;
  15. URL url = new URL(down_url);
  16. HttpURLConnection httpURLConnection = (HttpURLConnection) url
  17. .openConnection();
  18. httpURLConnection.setConnectTimeout(TIMEOUT);
  19. httpURLConnection.setReadTimeout(TIMEOUT);
  20. // 獲取下載文件的size
  21. totalSize = httpURLConnection.getContentLength();
  22. if (httpURLConnection.getResponseCode() == 404) {
  23. throw new Exception("fail!");
  24. }
  25. inputStream = httpURLConnection.getInputStream();
  26. outputStream = new FileOutputStream(file, false);// 文件存在則覆蓋掉
  27. byte buffer[] = new byte[1024];
  28. int readsize = 0;
  29. while ((readsize = inputStream.read(buffer)) != -1) {
  30. outputStream.write(buffer, 0, readsize);
  31. downloadCount += readsize;// 時時獲取下載到的大小
  32. /**
  33. * 每次增張5%
  34. */
  35. if (updateCount == 0
  36. || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
  37. updateCount += down_step;
  38. // 改變通知欄
  39. // notification.setLatestEventInfo(this, "正在下載...", updateCount
  40. // + "%" + "", pendingIntent);
  41. contentView.setTextViewText(R.id.notificationPercent,
  42. updateCount + "%");
  43. contentView.setProgressBar(R.id.notificationProgress, 100,
  44. updateCount, false);
  45. // show_view
  46. notificationManager.notify(notification_id, notification);
  47. }
  48. }
  49. if (httpURLConnection != null) {
  50. httpURLConnection.disconnect();
  51. }
  52. inputStream.close();
  53. outputStream.close();
  54. return downloadCount;
  55. }

注釋已經寫的很詳細,相信大家都看的明白,如果哪裡有不足的地方,請留您吉言指出.

這裡我用別的app代替了,簡單省事,正常的話,你要對你的APP進行數字簽名.然後才可以進行升級應用.

示意圖:

提示有新版 開始升級 升級下載中 下載完畢,點擊安裝

Copyright © Linux教程網 All Rights Reserved