android之apk自动更新采用Notification通知提示并显示下载进度

首先整理一下apk自动更新的思路:1 比较服务器和本地apk的版本;2 如果服务器版本较新,怎么发出Notification通知用户下载;3用户点击开始下载;4下载完成发出用户提示用户点击安装;5 用户点击安装完成结束整个流程;

下面是效果图,可以先看下是否是你想要的效果咯,亲!

ok,接下来直接上代码。版本比较这个东西就不讲了,出发出Notification通知开始

 

[java][/java] view plaincopy

  1. //概要
  2. String tickerText = context.getResources().getText(R.string.app_name).toString()+”发现新版本,建议您更新!”;
  3. //标题
  4. String title = context.getResources().getText(R.string.app_name).toString()+”更新”;
  5. //内容
  6. String content= “点击更新”+context.getResources().getText(R.string.app_name).toString();
  7. //logo
  8. int icon = R.drawable.logo;
  9. Notification notification = new Notification(icon, tickerText, System.currentTimeMillis());
  10. Intent updateinte = new Intent(context,UpdateService.class);
  11. updateinte.putExtra(“url”,re);
  12. PendingIntent pendingIntent = PendingIntent.getService(context, 0, updateinte, 0);//点击打开service下载
  13. notification.setLatestEventInfo(context, title, content, pendingIntent);
  14. notification.defaults = Notification.DEFAULT_SOUND;
  15. notification.flags = Notification.FLAG_AUTO_CANCEL;
  16. NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  17. manager.notify(101, notification);

下面是service下载类。下面的代码我自己遇到两个问题,Notification版本兼容系问题在http://blog.csdn.net/caicongyang/article/details/10190727做了解释,下载完成后解析包出现问题在http://blog.csdn.net/caicongyang/article/details/10183095做了解析,其他的很简单!

 

 

[java][/java] view plaincopy

  1. /**
  2.  * 下载更新服务
  3.  * @author Tom.Cai
  4.  *
  5.  */
  6. public class UpdateService extends Service {
  7.     private String url = null;
  8.     // 通知栏
  9.     private NotificationManager updateNotificationManager = null;
  10.     private Notification updateNotification = null;
  11.     private String appName = null;
  12.     private String fileName = null;
  13.     private String updateDir = null;
  14.     //通知栏跳转Intent
  15.     @Override
  16.     public int onStartCommand(Intent intent, int flags, int startId) {
  17.         // 获取传值
  18.         url = intent.getStringExtra(“url”);
  19.         appName = getApplication().getResources().getText(R.string.app_name).toString();
  20.         if (url != null) {
  21.             fileName = url.substring(url.lastIndexOf(“/”)+1);
  22.             updateDir = Environment.getDataDirectory() + “/data/” + this.getPackageName() + “/files/”;
  23.             Intent nullIntent = new Intent();
  24.             PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);
  25.             // 创建文件
  26.             updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  27.             updateNotification = new Notification();
  28.             updateNotification.icon = R.drawable.logo;
  29.             updateNotification.tickerText = “正在更新” + appName;
  30.             updateNotification.setLatestEventInfo(getApplication(), “正在下载”+appName,”0%”, null);
  31.             updateNotification.defaults = Notification.DEFAULT_SOUND;
  32.             updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
  33.             updateNotification.contentIntent = pendingIntent;
  34.             updateNotificationManager.notify(101, updateNotification);
  35.             //开启线程现在
  36.             new Thread(new updateRunnable()).start();
  37.         }
  38.         return super.onStartCommand(intent, 0, 0);
  39.     }
  40.     private class updateRunnable implements Runnable {
  41.         Message message = updateHandler.obtainMessage();
  42.         public void run() {
  43.             message.what = 0;
  44.             try {
  45.                 long downloadSize = downloadUpdateFile(url);
  46.                 Log.i(“cai”, downloadSize/1024+””);
  47.                 if (downloadSize > 0) {
  48.                     // 下载成功
  49.                     updateHandler.sendMessage(message);
  50.                 }
  51.             } catch (Exception ex) {
  52.                 ex.printStackTrace();
  53.                 message.what = 1;
  54.                 // 下载失败
  55.                 updateHandler.sendMessage(message);
  56.             }
  57.         }
  58.     }
  59.     private Handler updateHandler = new Handler() {
  60.         @Override
  61.         public void handleMessage(Message msg) {
  62.             switch (msg.what) {
  63.             case 0:
  64.                 /*try {
  65.                     Runtime.getRuntime().exec(“chmod 777 ” + updateDir.getAbsolutePath());
  66.                     Runtime.getRuntime().exec(“chmod 777 ” + updateFile.getAbsolutePath());
  67.                 } catch (IOException e) {
  68.                     e.printStackTrace();
  69.                 }*/
  70.                 // 点击安装PendingIntent
  71.                 Intent installIntent = new Intent(Intent.ACTION_VIEW);
  72.                 //installIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED| Intent.FLAG_ACTIVITY_NEW_TASK);
  73.                 installIntent.setDataAndType(Uri.fromFile(new File(updateDir,fileName)),”application/vnd.android.package-archive”);
  74.                 //getApplication().startActivity(installIntent);*/
  75.                 PendingIntent updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);
  76.                 updateNotification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
  77.                 updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
  78.                 updateNotification.setLatestEventInfo(UpdateService.this,appName, “下载完成,点击安装”, updatePendingIntent);
  79.                 updateNotificationManager.notify(101, updateNotification);
  80.                 // 停止服务
  81.                 stopSelf();
  82.                 break;
  83.             case 1:
  84.                 Intent nullIntent = new Intent();
  85.                 PendingIntent pendingIntent = PendingIntent.getActivity(UpdateService.this, 10, nullIntent, 0);
  86.                 // 下载失败
  87.                 updateNotification.setLatestEventInfo(UpdateService.this,appName, “网络连接不正常,下载失败!”, pendingIntent);
  88.                 updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
  89.                 updateNotificationManager.notify(101, updateNotification);
  90.                 break;
  91.             default:
  92.                 stopSelf();
  93.             }
  94.         }
  95.     };
  96.     //下载
  97.     @SuppressLint(“WorldReadableFiles”)
  98.     public long downloadUpdateFile(String downloadUrl) throws Exception {
  99.         int downloadCount = 0;
  100.         int currentSize = 0;
  101.         long totalSize = 0;
  102.         int updateTotalSize = 0;
  103.         HttpURLConnection httpConnection = null;
  104.         InputStream is = null;
  105.         FileOutputStream fos = null;
  106.         try {
  107.             URL url = new URL(downloadUrl);
  108.             httpConnection = (HttpURLConnection)url.openConnection();
  109.             if(currentSize > 0) {
  110.                 httpConnection.setRequestProperty(“RANGE”, “bytes=” + currentSize + “-“);
  111.             }
  112.             httpConnection.setConnectTimeout(10000);
  113.             httpConnection.setReadTimeout(20000);
  114.             updateTotalSize = httpConnection.getContentLength();
  115.             if (httpConnection.getResponseCode() == 404) {
  116.                 throw new Exception(“fail!”);
  117.             }
  118.             is = httpConnection.getInputStream();
  119.            /* fos = new FileOutputStream(saveFile, false);*/
  120.             fos =  openFileOutput(fileName, MODE_WORLD_READABLE);
  121.             byte buffer[] = new byte[4096];
  122.             int readsize = 0;
  123.             while((readsize = is.read(buffer)) > 0){
  124.                 fos.write(buffer, 0, readsize);
  125.                 totalSize += readsize;
  126.                 //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
  127.                 if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){
  128.                     downloadCount += 10;
  129.                     Intent nullIntent = new Intent();
  130.                     PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);
  131.                     updateNotification.contentIntent = pendingIntent;
  132.                     updateNotification.setLatestEventInfo(UpdateService.this, appName+”正在下载”, (int)totalSize*100/updateTotalSize+”%”, null);
  133.                     updateNotificationManager.notify(101, updateNotification);
  134.                 }
  135.             }
  136.         } finally {
  137.             if(httpConnection != null) {
  138.                 httpConnection.disconnect();
  139.             }
  140.             if(is != null) {
  141.                 is.close();
  142.             }
  143.             if(fos != null) {
  144.                 fos.close();
  145.             }
  146.         }
  147.         return totalSize;
  148.     }
  149.     @Override
  150.     public IBinder onBind(Intent intent) {
  151.         return null;
  152.     }
  153. }

以上类并没有进行优化,仅可作为学习参考。欢迎留言讨论。。。

标签