Android如何更新app的版本

本文介绍了一个用于Android应用的自动更新服务实现方案。该方案通过后台服务监测新版本并下载更新包,同时利用通知栏展示下载进度。完成下载后会提示用户进行安装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. package com.runye.express.service;

  2. import java.io.FileOutputStream;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;

  8. import android.app.Notification;
  9. import android.app.NotificationManager;
  10. import android.app.PendingIntent;
  11. import android.app.Service;
  12. import android.content.Intent;
  13. import android.net.Uri;
  14. import android.os.Handler;
  15. import android.os.IBinder;
  16. import android.os.Message;
  17. import android.widget.RemoteViews;

  18. import com.runye.express.android.R;
  19. import com.runye.express.utils.FileUtils;
  20. import com.runye.express.utils.LogUtil;

  21. /***
  22. * s 更新版本

  23. * @author zhangjia

  24. */
  25. public class UpdateService extends Service {
  26.         private final String TAG = "UpdateService";
  27.         /** 超时 */
  28.         private static final int TIMEOUT = 10 * 1000;
  29.         /** 下载地址 */
  30.         private static final String down_url = "http://www.tyfind.com:8080/find-consumers-android-update/new/find-consumers-android.apk";
  31.         /** 下载成功 */
  32.         private static final int DOWN_OK = 1;
  33.         /** 下载失败 */
  34.         private static final int DOWN_ERROR = 0;
  35.         /***
  36.          * 创建通知栏
  37.          */
  38.         RemoteViews mViews;
  39.         /** 应用名称 */
  40.         private String app_name;
  41.         /** 通知管理器 */
  42.         private NotificationManager notificationManager;
  43.         /** 通知 */
  44.         private Notification notification;
  45.         /** 点击通知跳转 */
  46.         private Intent mUpdateIntent;
  47.         /** 等待跳转 */
  48.         private PendingIntent mPendingIntent;
  49.         /** 通知ID */
  50.         private final int notification_id = 0;

  51.         @Override
  52.         public IBinder onBind(Intent arg0) {
  53.                 return null;
  54.         }

  55.         @Override
  56.         public int onStartCommand(Intent intent, int flags, int startId) {
  57.                 LogUtil.d(TAG, "UpdateService+onStartCommand");
  58.                 app_name = getResources().getString(R.string.app_name);
  59.                 // 创建文件
  60.                 FileUtils.createFile(app_name);

  61.                 createNotification();

  62.                 createThread();

  63.                 return super.onStartCommand(intent, flags, startId);

  64.         }

  65.         /**
  66.          * 
  67.          * @Description: 创建通知
  68.          * [url=home.php?mod=space&uid=309376]@return[/url] void
  69.          */
  70.         public void createNotification() {
  71.                 notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  72.                 android.app.Notification.Builder builder = new Notification.Builder(this);
  73.                 mViews = new RemoteViews(getPackageName(), R.layout.notification_item);
  74.                 mViews.setImageViewResource(R.id.notificationImage, R.drawable.ic_launcher);
  75.                 mViews.setTextViewText(R.id.notificationTitle, "Find物流版正在下载");
  76.                 mViews.setTextViewText(R.id.notificationPercent, "0%");
  77.                 mViews.setProgressBar(R.id.notificationProgress, 100, 0, false);
  78.                 builder.setContent(mViews);
  79.                 mUpdateIntent = new Intent(Intent.ACTION_MAIN);
  80.                 mUpdateIntent.addCategory(Intent.CATEGORY_HOME);
  81.                 mPendingIntent = PendingIntent.getActivity(this, 0, mUpdateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  82.                 builder.setContentIntent(mPendingIntent);
  83.                 builder.setTicker("开始下载,点击可查看");
  84.                 builder.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis()).setAutoCancel(true);// 设置可以清除
  85.                 notification = builder.getNotification();
  86.                 notificationManager.notify(notification_id, notification);
  87.         }

  88.         /***
  89.          * 开线程下载
  90.          */
  91.         public void createThread() {
  92.                 /***
  93.                  * 更新UI
  94.                  */
  95.                 final Handler handler = new Handler() {
  96.                         @Override
  97.                         public void handleMessage(Message msg) {
  98.                                 switch (msg.what) {
  99.                                 case DOWN_OK:
  100.                                         InstallationAPK();
  101.                                         break;
  102.                                 case DOWN_ERROR:
  103.                                         break;

  104.                                 default:
  105.                                         stopSelf();
  106.                                         break;
  107.                                 }

  108.                         }

  109.                 };

  110.                 final Message message = new Message();

  111.                 new Thread(new Runnable() {
  112.                         @Override
  113.                         public void run() {

  114.                                 try {
  115.                                         long downloadSize = downloadUpdateFile(down_url, FileUtils.updateFile.toString());
  116.                                         if (downloadSize > 0) {
  117.                                                 // 下载成功
  118.                                                 message.what = DOWN_OK;
  119.                                                 handler.sendMessage(message);
  120.                                         }

  121.                                 } catch (Exception e) {
  122.                                         e.printStackTrace();
  123.                                         message.what = DOWN_ERROR;
  124.                                         handler.sendMessage(message);
  125.                                 }

  126.                         }
  127.                 }).start();
  128.         }

  129.         /**
  130.          * 
  131.          * @Description: 自动安装
  132.          * @return void
  133.          */
  134.         private void InstallationAPK() {
  135.                 notificationManager.cancel(notification_id);
  136.                 // 停止服务
  137.                 stopSelf();
  138.                 // 下载完成,点击安装
  139.                 Uri uri = Uri.fromFile(FileUtils.updateFile);
  140.                 Intent intent = new Intent(Intent.ACTION_VIEW);
  141.                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  142.                 intent.setDataAndType(uri, "application/vnd.android.package-archive");
  143.                 startActivity(intent);

  144.         }

  145.         /***
  146.          * 下载文件
  147.          * 
  148.          * @return
  149.          * @throws MalformedURLException
  150.          */
  151.         public long downloadUpdateFile(String down_url, String file) throws Exception {
  152.                 int down_step = 5;// 提示step
  153.                 int totalSize;// 文件总大小
  154.                 int downloadCount = 0;// 已经下载好的大小
  155.                 int updateCount = 0;// 已经上传的文件大小
  156.                 InputStream inputStream;
  157.                 OutputStream outputStream;
  158.                 URL url = new URL(down_url);
  159.                 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  160.                 httpURLConnection.setConnectTimeout(TIMEOUT);
  161.                 httpURLConnection.setReadTimeout(TIMEOUT);
  162.                 // 获取下载文件的size
  163.                 totalSize = httpURLConnection.getContentLength();
  164.                 if (httpURLConnection.getResponseCode() == 404) {
  165.                         throw new Exception("fail!");
  166.                 }
  167.                 inputStream = httpURLConnection.getInputStream();
  168.                 outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
  169.                 byte buffer[] = new byte[1024];
  170.                 int readsize = 0;
  171.                 while ((readsize = inputStream.read(buffer)) != -1) {
  172.                         outputStream.write(buffer, 0, readsize);
  173.                         downloadCount += readsize;// 时时获取下载到的大小
  174.                         /**
  175.                          * 每次增张5%
  176.                          */
  177.                         if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
  178.                                 updateCount += down_step;
  179.                                 mViews.setTextViewText(R.id.notificationPercent, updateCount + "%");
  180.                                 mViews.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
  181.                                 notificationManager.notify(notification_id, notification);

  182.                         }

  183.                 }
  184.                 if (httpURLConnection != null) {
  185.                         httpURLConnection.disconnect();
  186.                 }
  187.                 inputStream.close();
  188.                 outputStream.close();

  189.                 return downloadCount;

  190.         }

  191. }
复制代码


在需要用的地方,比如登陆的时候检查服务器与本地的版本
  1. private void checkVersion() {
  2.                 if (NetWork.isNetworkConnected(LoginActivity.this)) {
  3.                         LogUtil.d(TAG, "开始检测更新\n");
  4.                         if (MyApplication.getInstance().localVersion < MyApplication.getInstance().serverVersion) {
  5.                                 LogUtil.d(TAG, "有新版本,开始更新\n" + "本地version:" + MyApplication.getInstance().localVersion
  6.                                                 + "\n服务器version:" + MyApplication.getInstance().serverVersion);
  7.                                 // 发现新版本,提示用户更新
  8.                                 AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
  9.                                 alert.setTitle("软件升级").setMessage("发现新版本,建议立即更新使用.")
  10.                                                 .setPositiveButton("更新", new DialogInterface.OnClickListener() {
  11.                                                         @Override
  12.                                                         public void onClick(DialogInterface dialog, int which) {
  13.                                                                 // 开启更新服务UpdateService
  14.                                                                 updateIntent = new Intent(LoginActivity.this, UpdateService.class);
  15.                                                                 startService(updateIntent);
  16.                                                         }
  17.                                                 }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
  18.                                                         @Override
  19.                                                         public void onClick(DialogInterface dialog, int which) {
  20.                                                                 dialog.dismiss();
  21.                                                         }
  22.                                                 });
  23.                                 alert.create().show();

  24.                         } else {
  25.                                 LogUtil.d(TAG, "没有新版本,无需更新");
  26.                         }
  27.                 }

  28.         }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值