Android检测版本更新 实现逻辑,UI效果自己处理

一个版本更新类:



[java]  view plain copy
  1. import java.io.File;  
  2.   
  3. import android.app.DownloadManager;  
  4. import android.app.DownloadManager.Request;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.content.IntentFilter;  
  9. import android.content.SharedPreferences;  
  10. import android.content.pm.PackageInfo;  
  11. import android.content.pm.PackageManager.NameNotFoundException;  
  12. import android.database.Cursor;  
  13. import android.net.Uri;  
  14. import android.os.Environment;  
  15. import android.preference.PreferenceManager;  
  16. import android.view.View;  
  17. import android.webkit.MimeTypeMap;  
  18.   
  19. /** 
  20.  * app版本更新类 需要以下权限 <br> 
  21.  * <uses-permission 
  22.  * android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /><br> 
  23.  * <uses-permission android:name="android.permission.INTERNET" /><br> 
  24.  * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><br> 
  25.  *  
  26.  * @author Administrator 
  27.  * 
  28.  */  
  29. public class VersionManager {  
  30.   
  31.     private Context context;  
  32.     private AppVersion appVersion;  
  33.     private DownloadManager downloadManager;  
  34.     private SharedPreferences prefs;  
  35.     private static final String DL_ID = "update_app_id";  
  36.     // 文件在sd卡的真实目录  
  37.     private String apkAbsolutePath;  
  38.   
  39.     public void setOnUpdateListener(OnUpdateListener listener) {  
  40.         this.listener = listener;  
  41.     }  
  42.   
  43.     private OnUpdateListener listener;  
  44.   
  45.     public void setAppVersion(AppVersion appVersion) {  
  46.         this.appVersion = appVersion;  
  47.     }  
  48.   
  49.     private static VersionManager instance = null;  
  50.   
  51.     public static VersionManager getInstance(Context context,  
  52.             AppVersion appVersion) {  
  53.         if (instance == null) {  
  54.             instance = new VersionManager(context, appVersion);  
  55.         }  
  56.         return instance;  
  57.     }  
  58.   
  59.     private VersionManager(Context context, AppVersion appVersion) {  
  60.         this.appVersion = appVersion;  
  61.         this.context = context;  
  62.         apkAbsolutePath = getSDPath() + appVersion.getFilePath() + "/"  
  63.                 + appVersion.getFileName();  
  64.         downloadManager = (DownloadManager) context  
  65.                 .getSystemService(Context.DOWNLOAD_SERVICE);  
  66.         prefs = PreferenceManager.getDefaultSharedPreferences(context);  
  67.     }  
  68.   
  69.     public void checkUpdateInfo() {  
  70.   
  71.         String localVersion = getVersionCode(context) + "";  
  72.         // 这里只要两个版本不一致就更新,不考虑版本降级的情况...  
  73.         if (!localVersion.equals(appVersion.getVersionCode())) {  
  74.             listener.hasNewVersion(true);  
  75.         } else {  
  76.             listener.hasNewVersion(false);  
  77.         }  
  78.     }  
  79.   
  80.     /** 
  81.      * 获取版本号(内部识别号) 
  82.      *  
  83.      * @param context 
  84.      * @return 
  85.      */  
  86.     private int getVersionCode(Context context) {  
  87.         try {  
  88.             PackageInfo pi = context.getPackageManager().getPackageInfo(  
  89.                     context.getPackageName(), 0);  
  90.             return pi.versionCode;  
  91.         } catch (NameNotFoundException e) {  
  92.             e.printStackTrace();  
  93.             return -1;  
  94.         }  
  95.     }  
  96.   
  97.     /** 
  98.      * 下载文件 
  99.      */  
  100.     public void downLoad() {  
  101.         if (!isSdCardExist()) {  
  102.             listener.onError("文件无法下载请检测您的sd卡");  
  103.             return;  
  104.         }  
  105.         if (isFileExist(apkAbsolutePath)) {  
  106.             // 如果文件已经存在则安装app  
  107.             installApk();  
  108.             return;  
  109.         }  
  110.         // 开始下载  
  111.         Uri resource = Uri.parse(appVersion.getApkUrl());  
  112.         DownloadManager.Request request = new DownloadManager.Request(resource);  
  113.         request.setAllowedNetworkTypes(Request.NETWORK_MOBILE  
  114.                 | Request.NETWORK_WIFI);  
  115.         request.setAllowedOverRoaming(false);  
  116.         // 设置文件类型  
  117.         MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
  118.         String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap  
  119.                 .getFileExtensionFromUrl(appVersion.getApkUrl()));  
  120.         request.setMimeType(mimeString);  
  121.         // 在通知栏中显示  
  122.         request.setNotificationVisibility(View.VISIBLE);  
  123.         request.setVisibleInDownloadsUi(true);  
  124.         request.setDestinationInExternalPublicDir(  
  125.                 "/" + appVersion.getFilePath() + "/", appVersion.getFileName());  
  126.         request.setTitle("版本更新...");  
  127.         long id = downloadManager.enqueue(request);  
  128.         // 保存id  
  129.         prefs.edit().putLong(DL_ID, id).commit();  
  130.         // 注册广播监听下载  
  131.         context.registerReceiver(receiver, new IntentFilter(  
  132.                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
  133.     }  
  134.   
  135.     private void installApk() {  
  136.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  137.         intent.setDataAndType(Uri.fromFile(new File(apkAbsolutePath)),  
  138.                 "application/vnd.android.package-archive");  
  139.         context.startActivity(intent);  
  140.     }  
  141.   
  142.     private boolean isSdCardExist() {  
  143.         return Environment.getExternalStorageState().equals(  
  144.                 Environment.MEDIA_MOUNTED);  
  145.     }  
  146.   
  147.     private String getSDPath() {  
  148.         if (isSdCardExist()) {  
  149.             return Environment.getExternalStorageDirectory() + "/";  
  150.         }  
  151.         return null;  
  152.     }  
  153.   
  154.     private boolean isFileExist(String path) {  
  155.         return new File(path).exists();  
  156.     }  
  157.   
  158.     private BroadcastReceiver receiver = new BroadcastReceiver() {  
  159.         @Override  
  160.         public void onReceive(Context context, Intent intent) {  
  161.             DownloadManager.Query query = new DownloadManager.Query();  
  162.             query.setFilterById(prefs.getLong(DL_ID, 0));  
  163.             Cursor c = downloadManager.query(query);  
  164.             if (c.moveToFirst()) {  
  165.                 int status = c.getInt(c  
  166.                         .getColumnIndex(DownloadManager.COLUMN_STATUS));  
  167.                 switch (status) {  
  168.                 case DownloadManager.STATUS_RUNNING:  
  169.                     // 正在下载,不做任何事情  
  170.                     listener.onDownloading();  
  171.                     break;  
  172.                 case DownloadManager.STATUS_SUCCESSFUL:  
  173.                     // 下载完成首先取消注册广播,然后安装app  
  174.                     listener.onSuccess();  
  175.                     context.unregisterReceiver(receiver);  
  176.                     installApk();  
  177.                     break;  
  178.                 case DownloadManager.STATUS_FAILED:  
  179.                     // 下载失败 清除已下载的内容,重新下载  
  180.                     context.unregisterReceiver(receiver);  
  181.                     listener.onError("下载失败,请重试");  
  182.                     downloadManager.remove(prefs.getLong(DL_ID, 0));  
  183.                     prefs.edit().clear().commit();  
  184.                     break;  
  185.                 }  
  186.             }  
  187.         }  
  188.     };  
  189.   
  190.     /** 
  191.      * app版本信息 
  192.      *  
  193.      * @author sunger 
  194.      * 
  195.      */  
  196.     public static class AppVersion {  
  197.         // apk下载url  
  198.         private String apkUrl;  
  199.         // apk最新版本  
  200.         private String versionCode;  
  201.   
  202.         public String getVersionCode() {  
  203.             return versionCode;  
  204.         }  
  205.   
  206.         public void setVersionCode(String versionCode) {  
  207.             this.versionCode = versionCode;  
  208.         }  
  209.   
  210.         public String getFileName() {  
  211.             return fileName;  
  212.         }  
  213.   
  214.         public void setFileName(String fileName) {  
  215.             this.fileName = fileName;  
  216.         }  
  217.   
  218.         private String fileName;  
  219.   
  220.         public String getFilePath() {  
  221.             return filePath;  
  222.         }  
  223.   
  224.         public void setFilePath(String filePath) {  
  225.             this.filePath = filePath;  
  226.         }  
  227.   
  228.         /** 
  229.          * 文件在sd卡的相对路径 
  230.          */  
  231.         private String filePath;  
  232.   
  233.         public String getApkUrl() {  
  234.             return apkUrl;  
  235.         }  
  236.   
  237.         public void setApkUrl(String apkUrl) {  
  238.             this.apkUrl = apkUrl;  
  239.         }  
  240.   
  241.     }  
  242.   
  243.     public interface OnUpdateListener {  
  244.         /** 
  245.          * 是否有新版本更新,如果为true这里开始调用 
  246.          *  
  247.          * @param has 
  248.          */  
  249.         public void hasNewVersion(boolean has);  
  250.   
  251.         /** 
  252.          * 正在开始下载 
  253.          */  
  254.         public void onDownloading();  
  255.   
  256.         /** 
  257.          * 下载完成,并且安装成功 
  258.          */  
  259.         public void onSuccess();  
  260.   
  261.         /** 
  262.          * 更新失败 
  263.          *  
  264.          * @param msg 
  265.          *            失败的消息 
  266.          */  
  267.         public void onError(String msg);  
  268.   
  269.     }  
  270.   
  271. }  


1.首先需要加入权限:

[java]  view plain copy
  1. <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />  
  2. <uses-permission android:name="android.permission.INTERNET" />  
  3. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

2.使用,注意这里的AppVersion 信息是调用服务器接口获取的,然后设置进对象。表哥表示不喜欢配置服务器xml的方法,直接用接口返回数据,

自己去解析。。。


[java]  view plain copy
  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.widget.Toast;  
  4.   
  5. import com.sunger.versionupdate.VersionManager.AppVersion;  
  6. import com.sunger.versionupdate.VersionManager.OnUpdateListener;  
  7.   
  8. public class MainActivity extends Activity {  
  9.   
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_main);  
  14.         AppVersion version = new AppVersion();  
  15.         // 设置文件url  
  16.         version.setApkUrl("http://222.73.3.43/sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk?mkey=5523a9bb6eb200cf&f=188a&p=.apk");  
  17.         // 设置文件名  
  18.         version.setFileName("手机QQ");  
  19.         // 设置文件在sd卡的目录  
  20.         version.setFilePath("update");  
  21.         // 设置app当前版本号  
  22.         version.setVersionCode(2 + "");  
  23.         final VersionManager manager = VersionManager  
  24.                 .getInstance(this, version);  
  25.         manager.setOnUpdateListener(new OnUpdateListener() {  
  26.   
  27.             @Override  
  28.             public void onSuccess() {  
  29.                 Toast.makeText(MainActivity.this"下载成功等待安装", Toast.LENGTH_LONG)  
  30.                         .show();  
  31.             }  
  32.   
  33.             @Override  
  34.             public void onError(String msg) {  
  35.                 Toast.makeText(MainActivity.this"更新失败" + msg,  
  36.                         Toast.LENGTH_LONG).show();  
  37.             }  
  38.   
  39.             @Override  
  40.             public void onDownloading() {  
  41.                 Toast.makeText(MainActivity.this"正在下载...", Toast.LENGTH_LONG)  
  42.                         .show();  
  43.             }  
  44.   
  45.             @Override  
  46.             public void hasNewVersion(boolean has) {  
  47.                 if (has) {  
  48.                     Toast.makeText(MainActivity.this"检测到有新版本",  
  49.                             Toast.LENGTH_LONG).show();  
  50.                     manager.downLoad();  
  51.                 }  
  52.             }  
  53.         });  
  54.         manager.checkUpdateInfo();  
  55.   
  56.     }  

完了表哥是不是好流弊... 生气 尴尬
源码下载
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值