}
public class VersionManager {private Context context; private AppVersion appVersion; private DownloadManager downloadManager; private SharedPreferences prefs; private static final String DL_ID = "update_app_id"; public Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); // 文件在sd卡的真实目录 private String apkAbsolutePath; public void setOnUpdateListener(OnUpdateListener listener) { this.listener = listener; } private OnUpdateListener listener; public void setAppVersion(AppVersion appVersion) { this.appVersion = appVersion; } private static VersionManager instance = null; public static VersionManager getInstance(Context context, AppVersion appVersion) { if (instance == null) { instance = new VersionManager(context, appVersion); } return instance; } private VersionManager(Context context, AppVersion appVersion) { this.appVersion = appVersion; this.context = context; apkAbsolutePath = getSDPath() + appVersion.getFilePath() + "/" + appVersion.getFileName(); downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(context); } public void checkUpdateInfo() {//根据是否存在下载链接 String localVersion=appVersion.getApkUrl(); if(localVersion.equals(appVersion.getApkUrl())){//有新版本 listener.hasNewVersion(true); }else{//没有新版本 listener.hasNewVersion(false); } /* String localVersion = Utils.getVersionCode(context) + ""; // 这里只要两个版本不一致就更新,不考虑版本降级的情况... if (!localVersion.equals(appVersion.getVersionCode())) { listener.hasNewVersion(true); } else { listener.hasNewVersion(false); }*/ } public void queryDownloadStatus(){ DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(prefs.getLong(DL_ID, 0)); Log.d("status","downloadManagerId="+Long.toString(prefs.getLong(DL_ID, 0))); Cursor c = downloadManager.query(query); if (c.moveToFirst()) { int status = c.getInt(c .getColumnIndex(DownloadManager.COLUMN_STATUS)); switch (status) { case DownloadManager.STATUS_RUNNING: // 正在下载,不做任何事情 Log.d("manager","STATUS_RUNNING()"); listener.onDownloading(); break; case DownloadManager.STATUS_SUCCESSFUL: Log.d("manager","STATUS_SUCCESSFUL()"); // 下载完成首先取消注册广播,然后安装app listener.onSuccess(); context.unregisterReceiver(receiver); installApk(); break; case DownloadManager.STATUS_FAILED: Log.d("manager","STATUS_FAILED()"); // 下载失败 清除已下载的内容,重新下载 context.unregisterReceiver(receiver); listener.onError("下载失败,请重试"); downloadManager.remove(prefs.getLong(DL_ID, 0)); prefs.edit().clear().commit(); break; } } } /** * 下载文件 */ public void downLoad() { if (!isSdCardExist()) { listener.onError("文件无法下载请检测您的sd卡"); return; } if (isFileExist(apkAbsolutePath)) { // 如果文件已经存在则安装app installApk(); return; } // 开始下载 Uri resource = Uri.parse(appVersion.getApkUrl()); DownloadManager.Request request = new DownloadManager.Request(resource); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); request.setAllowedOverRoaming(false); // 设置文件类型 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap .getFileExtensionFromUrl(appVersion.getApkUrl())); request.setMimeType(mimeString); // 在通知栏中显示 request.setNotificationVisibility(View.VISIBLE); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalPublicDir( "/" + appVersion.getFilePath() + "/", appVersion.getFileName()); request.setTitle("QQ"); long id = downloadManager.enqueue(request); /* downloadObserver = new DownloadChangeObserver(null); context.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);*/ // 保存id prefs.edit().putLong(DL_ID, id).commit(); // 注册广播监听下载 context.registerReceiver(receiver, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } private void installApk() {//安装apk Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(apkAbsolutePath)), "application/vnd.android.package-archive"); context.startActivity(intent); } private boolean isSdCardExist() { return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } private String getSDPath() { if (isSdCardExist()) { return Environment.getExternalStorageDirectory() + "/"; } return null; } private boolean isFileExist(String path) { return new File(path).exists(); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { queryDownloadStatus(); } }; /** * app版本信息 * * @author sunger * */ public static class AppVersion { // apk下载url private String apkUrl; // apk最新版本 private int versionCode; public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } private String fileName; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } /** * 文件在sd卡的相对路径 */ private String filePath; public String getApkUrl() { return apkUrl; } public void setApkUrl(String apkUrl) { this.apkUrl = apkUrl; } } public interface OnUpdateListener { /** * 是否有新版本更新,如果为true这里开始调用 * * @param has */ public void hasNewVersion(boolean has); /** * 正在开始下载 */ public void onDownloading(); /** * 下载完成,并且安装成功 */ public void onSuccess(); /** * 更新失败 * * @param msg * 失败的消息 */ public void onError(String msg); }}
/** * Created by Shi on 2017/2/7. * 检查版本更新 */public class CheckUpdate extends AsyncTask<String, Void, String> { private int versionCode; private Context context; private Handler handler; public CheckUpdate(Handler handler,Context context, int versionCode){ this.context=context; this.handler=handler; this.versionCode=versionCode; } @Override protected String doInBackground(String... strings) { String result = null; try { Log.d("CheckUpdate","versionCode=="+versionCode);// result = FocusService.getInstance(context).doCheckUpdate(String.valueOf(versionCode));网络请求结果 } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result);// if(null !=result){ Log.d("CheckUpdate","result="+result); Message message=Message.obtain(); message.what=021;// message.obj=result; message.obj="http://222.73.3.43/sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk?mkey=5523a9bb6eb200cf&f=188a&p=.apk";//给一个假值 handler.sendMessage(message);// }// else{// Log.d("CheckUpdate","失败");// } }}
Demo下载地址:http://download.csdn.net/detail/sinat_28238111/9750008
新闻热点
疑难解答