关闭

Android 一个强大实用的版本升级demo(thread+service+Notification)

标签: android应用
216人阅读 评论(0) 收藏 举报
分类:
11.png 点击马上更新 33.png 点击后台更新 66.png 
效果apk:  TestVersionUpdate.apk (21.86 KB, 下载次数: 78) 
源码:  versionUpdate.zip (90.25 KB, 下载次数: 1312) 

第一步:获取本机app版本:
  1. public int getVerCode(Context _context,String _package) {
  2. int verCode = -1;
  3. try {
  4. verCode = _context.getPackageManager().getPackageInfo(
  5. _package, 0).versionCode;
  6. } catch (NameNotFoundException e) {
  7. }
  8. return verCode;
  9. }
复制代码
第二步:线程从服务端下载当前版本以及升级提示:
  1. public JSONObject getJsonObject(String Url) {
  2. HttpClient client = new DefaultHttpClient();
  3. StringBuilder sb = new StringBuilder();
  4. String js = null;JSONObject son=null;
  5. HttpGet myget = new HttpGet(Url); 
  6. try {
  7. HttpParams params = new BasicHttpParams();
  8. HttpConnectionParams.setConnectionTimeout(params, 8000);
  9. HttpResponse response = client.execute(myget);
  10. BufferedReader reader = new BufferedReader(new InputStreamReader(
  11. response.getEntity().getContent()));
  12. for (String s = reader.readLine(); s != null; s = reader.readLine()) {
  13. sb.append(s);
  14. }
  15. js = sb.toString();
  16. son = new JSONObject(js);
  17. } catch (Exception e) {
  18. // TODO Auto-generated catch block
  19. System.out.println("异常-》下载转化JSON");
  20. return null;
  21. }
  22. return son;
  23. }
复制代码
第三步:进行版本号对比,若有新版本,进行版本升级提示,builder使用自定义view。
  1. LinearLayout ll = (LinearLayout) LayoutInflater.from(TestVersionUpdateActivity.this).inflate(
  2. R.layout.layout_loadapk, null);
  3. pb = (ProgressBar) ll.findViewById(R.id.down_pb);
  4. tv = (TextView) ll.findViewById(R.id.tv);
  5. Builder builder = new Builder(TestVersionUpdateActivity.this);
  6. builder.setView(ll);builder.setTitle("版本更新进度提示");
  7. builder.setNegativeButton("后台下载",
  8. new DialogInterface.OnClickListener() {
  9. @Override
  10. public void onClick(DialogInterface dialog, int which) {
  11. Intent intent=new Intent(TestVersionUpdateActivity.this, VersionService.class); 
  12. startService(intent);
  13. dialog.dismiss();
  14. }
  15. });

  16. builder.show();
  17. new Thread() {
  18. public void run() {
  19. loadFile("http://1.nightman.sinaapp.com/test/good.zip");
  20. }
  21. }.start();
复制代码
第四步,进行更新
  1. public void loadFile(String url) {
  2. HttpClient client = new DefaultHttpClient();
  3. HttpGet get = new HttpGet(url);
  4. HttpResponse response;
  5. try {
  6. response = client.execute(get);

  7. HttpEntity entity = response.getEntity();
  8. int length = (int) entity.getContentLength();

  9. InputStream is = entity.getContent();
  10. FileOutputStream fileOutputStream = null;
  11. if (is != null) {
  12. File file = new File(Environment.getExternalStorageDirectory(),
  13. "NightMan.apk");
  14. fileOutputStream = new FileOutputStream(file);
  15. byte[] buf = new byte[1024];
  16. int ch = -1;
  17. int count = 0;
  18. while ((ch = is.read(buf)) != -1) {
  19. fileOutputStream.write(buf, 0, ch);
  20. count += ch;
  21. sendMsg(1,(int) (count*100/length));
  22. }
  23. }
  24. sendMsg(2,0);
  25. fileOutputStream.flush();
  26. if (fileOutputStream != null) {
  27. fileOutputStream.close();
  28. }
  29. } catch (Exception e) {
  30. sendMsg(-1,0);
  31. }
  32. }
  33. private void sendMsg(int flag,int c) {
  34. Message msg = new Message();
  35. msg.what = flag;msg.arg1=c;
  36. handler.sendMessage(msg);
  37. }
  38. private Handler handler = new Handler() {
  39. @Override
  40. public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
  41. if (!Thread.currentThread().isInterrupted()) {
  42. switch (msg.what) {
  43. case 1:
  44. pb.setProgress(msg.arg1);
  45. loading_process = msg.arg1;
  46. tv.setText("已为您加载了:" + loading_process + "%");
  47. break;
  48. case 2:
  49. Intent intent = new Intent(Intent.ACTION_VIEW);
  50. intent.setDataAndType(Uri.fromFile(new File(Environment
  51. .getExternalStorageDirectory(), "NightMan.apk")),
  52. "application/vnd.android.package-archive");
  53. startActivity(intent);
  54. break;
  55. case -1:
  56. String error = msg.getData().getString("error");
  57. Toast.makeText(TestVersionUpdateActivity.this, error, 1).show();
  58. break;
  59. }
  60. }
  61. super.handleMessage(msg);
  62. }
  63. };
复制代码
后台下载service循环handler
  1. private Handler mHandler = new Handler() {
  2. @Override
  3. public void handleMessage(Message msg) {
  4. // 1为出现,2为隐藏
  5. if(TestVersionUpdateActivity.loading_process>99){
  6. notificationMrg.cancel(0);
  7. stopSelf();
  8. return;
  9. }
  10. if(TestVersionUpdateActivity.loading_process>old_process){
  11. displayNotificationMessage(TestVersionUpdateActivity.loading_process);
  12. }

  13. new Thread() {
  14. public void run() {
  15. isFirstStart=false;
  16. Message msg = mHandler.obtainMessage();
  17. mHandler.sendMessage(msg);
  18. }
  19. }.start();
  20. old_process =TestVersionUpdateActivity.loading_process;
  21. }
  22. };
复制代码
有需要改进的地方望大哥们多踢踢BUG

应部分朋友的需求,这边上一下服务端的代码

服务器端以PHP为例,输出一个JSON格式的字符串
<?php
echo '{        "version":2,
        "content":[{"id":0,"text":"增加了摇一摇自动排列频道的功能"},
{"id":1,"text":"优化了拖拽缓冲的效果"},
{"id":2,"text":"改善了PATH菜单用户体验"},
{"id":3,"text":"添加了更多名人趣事"}
]}
        ';
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:26706次
    • 积分:1070
    • 等级:
    • 排名:千里之外
    • 原创:81篇
    • 转载:23篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论