在程序启动的时候检测服务器上有没有对应版本更新,如果有更新,提示用户是否更新。
在程序启动的时候首先调用更新模块检测服务器上存放的版本号跟当前程序的版本号如果大于当前版本号,弹出更新对话框,如果用户选择更新,则显示当前更新状态,然后替换当前程序。
程序调用版本更新检测:
private UpdateManager updateMan; private ProgressDialog updateProgressDialog; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //没有判断网路是否连接 //检查是否有更新 //如果有更新提示下载 updateMan = new UpdateManager(Update_TestActivity.this, appUpdateCb); updateMan.checkUpdate(); }
执行检测版本号以及回调更新提示
下载更新文件等实现:
package update.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONArray; import org.json.JSONObject; import com.trinet.util.NetHelper; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.util.Log; public class UpdateManager { private String curVersion; private String newVersion; private int curVersionCode; private int newVersionCode; private String updateInfo; private UpdateCallback callback; private Context ctx; private int progress; private Boolean hasNewVersion; private Boolean canceled; //存放更新APK文件的路径 public static final String UPDATE_DOWNURL = "http://www.baidu.com/update/update_test.apk"; //存放更新APK文件相应的版本说明路径 public static final String UPDATE_CHECKURL = "http://www.baidu.com/update/update_verson.txt"; public static final String UPDATE_APKNAME = "update_test.apk"; //public static final String UPDATE_VERJSON = "ver.txt"; public static final String UPDATE_SAVENAME = "updateapk.apk"; private static final int UPDATE_CHECKCOMPLETED = 1; private static final int UPDATE_DOWNLOADING = 2; private static final int UPDATE_DOWNLOAD_ERROR = 3; private static final int UPDATE_DOWNLOAD_COMPLETED = 4; private static final int UPDATE_DOWNLOAD_CANCELED = 5; //从服务器上下载apk存放文件夹 private String savefolder = "/mnt/innerDisk/"; //private String savefolder = "/sdcard/"; //public static final String SAVE_FOLDER =Storage. // "/mnt/innerDisk"; public UpdateManager(Context context, UpdateCallback updateCallback) { ctx = context; callback = updateCallback; //savefolder = context.getFilesDir(); canceled = false; getCurVersion(); } public String getNewVersionName() { return newVersion; } public String getUpdateInfo() { return updateInfo; } private void getCurVersion() { try { PackageInfo pInfo = ctx.getPackageManager().getPackageInfo( ctx.getPackageName(), 0); curVersion = pInfo.versionName; curVersionCode = pInfo.versionCode; } catch (NameNotFoundException e) { Log.e("update", e.getMessage()); curVersion = "1.1.1000"; curVersionCode = 111000; } } public void checkUpdate() { hasNewVersion = false; new Thread(){ // *************************************************************** /** * @by wainiwann * */ @Override public void run() { Log.i("@@@@@", ">>>>>>>>>>>>>>>>>>>>>>>>>>>getServerVerCode() "); try { String verjson = NetHelper.httpStringGet(UPDATE_CHECKURL); Log.i("@@@@", verjson + "**************************************************"); JSONArray array = new JSONArray(verjson); if (array.length() > 0) { JSONObject obj = array.getJSONObject(0); try { newVersionCode = Integer.parseInt(obj.getString("verCode")); newVersion = obj.getString("verName"); updateInfo = ""; Log.i("newVerCode", newVersionCode + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); Log.i("newVerName", newVersion + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); if (newVersionCode > curVersionCode) { hasNewVersion = true; } } catch (Exception e) { newVersionCode = -1; newVersion = ""; updateInfo = ""; } } } catch (Exception e) { Log.e("update", e.getMessage()); } updateHandler.sendEmptyMessage(UPDATE_CHECKCOMPLETED); }; // *************************************************************** }.start(); } public void update() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.fromFile(new File(savefolder, UPDATE_SAVENAME)), "application/vnd.android.package-archive"); ctx.startActivity(intent); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public void downloadPackage() { new Thread() { @Override public void run() { try { URL url = new URL(UPDATE_DOWNURL); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.connect(); int length = conn.getContentLength(); InputStream is = conn.getInputStream(); File ApkFile = new File(savefolder,UPDATE_SAVENAME); if(ApkFile.exists()) { ApkFile.delete(); } FileOutputStream fos = new FileOutputStream(ApkFile); int count = 0; byte buf[] = new byte[512]; do{ int numread = is.read(buf); count += numread; progress =(int)(((float)count / length) * 100); updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOADING)); if(numread <= 0){ updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_COMPLETED); break; } fos.write(buf,0,numread); }while(!canceled); if(canceled) { updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_CANCELED); } fos.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR,e.getMessage())); } catch(IOException e){ e.printStackTrace(); updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR,e.getMessage())); } } }.start(); } public void cancelDownload() { canceled = true; } Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_CHECKCOMPLETED: callback.checkUpdateCompleted(hasNewVersion, newVersion); break; case UPDATE_DOWNLOADING: callback.downloadProgressChanged(progress); break; case UPDATE_DOWNLOAD_ERROR: callback.downloadCompleted(false, msg.obj.toString()); break; case UPDATE_DOWNLOAD_COMPLETED: callback.downloadCompleted(true, ""); break; case UPDATE_DOWNLOAD_CANCELED: callback.downloadCanceled(); default: break; } } }; public interface UpdateCallback { public void checkUpdateCompleted(Boolean hasUpdate, CharSequence updateInfo); public void downloadProgressChanged(int progress); public void downloadCanceled(); public void downloadCompleted(Boolean sucess, CharSequence errorMsg); } }
需要连接服务器模块:
package com.trinet.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class NetHelper { public static String httpStringGet(String url) throws Exception { return httpStringGet(url, "utf-8"); } /** * * * @param url * @return */ public static Drawable loadImage(String url) { try { return Drawable.createFromStream( (InputStream) new URL(url).getContent(), "test"); } catch (MalformedURLException e) { Log.e("exception", e.getMessage()); } catch (IOException e) { Log.e("exception", e.getMessage()); } return null; } public static String httpStringGet(String url, String enc) throws Exception { // This method for HttpConnection String page = ""; BufferedReader bufferedReader = null; try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpGet request = new HttpGet(); request.setHeader("Content-Type", "text/plain; charset=utf-8"); request.setURI(new URI(url)); HttpResponse response = client.execute(request); bufferedReader = new BufferedReader(new InputStreamReader(response .getEntity().getContent(), enc)); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + NL); } bufferedReader.close(); page = stringBuffer.toString(); Log.i("page", page); System.out.println(page + "page"); return page; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { Log.d("BBB", e.toString()); } } } } public static boolean checkNetWorkStatus(Context context) { boolean result; ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netinfo = cm.getActiveNetworkInfo(); if (netinfo != null && netinfo.isConnected()) { result = true; Log.i("NetStatus", "The net was connected"); } else { result = false; Log.i("NetStatus", "The net was bad!"); } return result; } }
以及提示对话框:
package com.trinet.util; import java.lang.reflect.Field; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.view.View; public class DialogHelper { public static void Alert(Context ctx, CharSequence title, CharSequence message, CharSequence okText, OnClickListener oklistener) { AlertDialog.Builder builder = createDialog(ctx, title, message); builder.setPositiveButton(okText, oklistener); builder.create().show(); } public static void Alert(Context ctx, int titleId, int messageId, int okTextId, OnClickListener oklistener) { Alert(ctx, ctx.getText(titleId), ctx.getText(messageId), ctx.getText(okTextId), oklistener); } public static void Confirm(Context ctx, CharSequence title, CharSequence message, CharSequence okText, OnClickListener oklistener, CharSequence cancelText, OnClickListener cancellistener) { AlertDialog.Builder builder = createDialog(ctx, title, message); builder.setPositiveButton(okText, oklistener); builder.setNegativeButton(cancelText, cancellistener); builder.create().show(); } public static void Confirm(Context ctx, int titleId, int messageId, int okTextId, OnClickListener oklistener, int cancelTextId, OnClickListener cancellistener) { Confirm(ctx, ctx.getText(titleId), ctx.getText(messageId), ctx.getText(okTextId), oklistener, ctx.getText(cancelTextId), cancellistener); } private static AlertDialog.Builder createDialog(Context ctx, CharSequence title, CharSequence message) { AlertDialog.Builder builder = new Builder(ctx); builder.setMessage(message); if(title!=null) { builder.setTitle(title); } return builder; } @SuppressWarnings("unused") private static AlertDialog.Builder createDialog(Context ctx,int titleId, int messageId) { AlertDialog.Builder builder = new Builder(ctx); builder.setMessage(messageId); builder.setTitle(titleId); return builder; } public static void ViewDialog(Context ctx, CharSequence title, View view, CharSequence okText, OnClickListener oklistener, CharSequence cancelText, OnClickListener cancellistener) { } public static void ViewDialog(Context ctx, int titleId, View view, int okTextId, OnClickListener oklistener, int cancelTextId, OnClickListener cancellistener) { ViewDialog(ctx, ctx.getText(titleId), view, ctx.getText(okTextId), oklistener, ctx.getText(cancelTextId), cancellistener); } // public static void SetDialogShowing(DialogInterface dialog, boolean showing) { try { Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); field.setAccessible(true); field.set(dialog, showing); } catch (Exception e) { e.printStackTrace(); } } }
下面是又更新的话执行回调函数提示用户:
// 自动更新回调函数 UpdateManager.UpdateCallback appUpdateCb = new UpdateManager.UpdateCallback() { public void downloadProgressChanged(int progress) { if (updateProgressDialog != null && updateProgressDialog.isShowing()) { updateProgressDialog.setProgress(progress); } } public void downloadCompleted(Boolean sucess, CharSequence errorMsg) { if (updateProgressDialog != null && updateProgressDialog.isShowing()) { updateProgressDialog.dismiss(); } if (sucess) { updateMan.update(); } else { DialogHelper.Confirm(Update_TestActivity.this, R.string.dialog_error_title, R.string.dialog_downfailed_msg, R.string.dialog_downfailed_btnnext, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { updateMan.downloadPackage(); } }, R.string.dialog_downfailed_btnnext, null); } } public void downloadCanceled() { // TODO Auto-generated method stub } public void checkUpdateCompleted(Boolean hasUpdate, CharSequence updateInfo) { if (hasUpdate) { DialogHelper.Confirm(Update_TestActivity.this, getText(R.string.dialog_update_title), getText(R.string.dialog_update_msg).toString() +updateInfo+ getText(R.string.dialog_update_msg2).toString(), getText(R.string.dialog_update_btnupdate), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { updateProgressDialog = new ProgressDialog( Update_TestActivity.this); updateProgressDialog .setMessage(getText(R.string.dialog_downloading_msg)); updateProgressDialog.setIndeterminate(false); updateProgressDialog .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); updateProgressDialog.setMax(100); updateProgressDialog.setProgress(0); updateProgressDialog.show(); updateMan.downloadPackage(); } },getText( R.string.dialog_update_btnnext), null); } } };
要记得给程序添加权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
测试源码下载:
相关推荐
本文实例讲述了Android程序自动更新功能模块的实现方法。分享给大家供大家参考,具体如下: 在程序启动的时候检测服务器上有没有对应版本更新,如果有更新,提示用户是否更新。 在程序启动的时候首先调用更新模块...
安卓程序本身实现自动更新的功能模块,修改下url直接就可以拿来用
本文给大家分享Android里应用版本更新功能这一块的实现。 一个好的应用软件都是需要好的维护,从初出版本到最后精品,这个过程需要版本不停的更新,那么如何让用户第一时间获取最新的应用安装包呢?那么就要求我们从...
Android编写极逼真的指南针 ,包括了传感器 自动定位模块,这里的指南针外观是调用的图片,程序主要是通过获取到的数值改变指南针图片转过的角度,主要涉及到获取管理服务、注册监听器、传感器值改变、精度改变、...
支持保留堆栈(可以区分不同文件和方法,并且实现在AS中自动日志定位) 支持分组打印(可以区分不同开发者, etc) 按需依赖 核心功能模块和定制特性完全分离,体积轻巧,并且全部支持Jcenter依赖。 扩展灵活 核心功能...
通过注解自动注入,反射会让程序变慢50~100毫秒左右,从体验感基本感觉不出来.硬件性能好的手机可以忽略,经过测试无需太大的担心。我是做外包的,初衷是在不影响项目质量的前提下减少我的工作量,而且BUG其他人改...
如果用过一些手机助手的朋友都知道,手机助手下载其他软件的更新程序后会自动静默更新。APK静默安装是指实现了在APK文件安装过程中不会出现系统安装对话框。不仅可以安装新的apk,也适用于更新旧的apk。更新apk必须...
第3章 Android程序设计基础 3.1 Android程序框架 3.1.1 Android项目目录结构 3.1.2 Android应用解析 3.2 Android的生命周期 3.3 Android程序U设计 3.4 小结 第4章 用户界面开发 4.1 用户界面开发详解 4.1.1 用户...
功能模块:1.实现服务的onCreate(),重写onbind()方法,销毁onDestroy()方法如果 Activity 绑定,Activity 就可以取到 IBinder 对象,可以直接调用对象的方法,相同应用内部不同组件绑定,可以使用内部类以及...
功能支持 不同module都能接收Application的onCreate等生命周期回调进行本module的初始化 不同module之间的页面跳转,自动打包传递参数 不同module之间的数据交互,接口参数对开发友好可见 页面跳转支持所有Intent可...
全书共分10章,主要以范例集的方式来讲述Android的知识点,详细介绍了开发Android的人机交互界面、Android常用的开发控件、使用Android手机收发短信等通信服务、开发Android手机的自动服务功能和娱乐多媒体功能以及...
第3章 Android程序设计基础 3.1 Android程序框架 3.1.1 Android项目目录结构 3.1.2 Android应用解析 3.2 Android的生命周期 3.3 Android程序U设计 3.4 小结 第4章 用户界面开发 4.1 用户界面开发...
Obfuscapk是一个模块化的Python工具,用于在不需要反汇编源代码的情况下混淆Android应用程序,因为在对反编译的smali代码,资源和清单应用了一些混淆技术之后, 用于反编译原始apk文件并构建新的应用程序。...
使用uiautomator2+pytest+allure进行Android的UI自动化测试 测试携程旅行App,首页-机票-机票搜索模块 简介 使用uiautomator2+pytest+allure进行Android的UI自动化测试 环境搭建 pytest框架 pip install pytest ...
详细介绍了开发Android的人机交互界面、Android常用的开发控件、使用Android手机收发短信等通信服务、开发Android手机的自动服务功能和娱乐多媒体功能以及整合Android与Aoogle强大的网络服务等内容,随书光盘中包括...
第3章 Android程序设计基础 3.1 Android程序框架 3.1.1 Android项目目录结构 3.1.2 Android应用解析 3.2 Android的生命周期 3.3 Android程序U设计 3.4 小结 第4章 用户界面开发 4.1 用户界面开发详解 4.1.1 用户...
QT,C++使用技巧,详细介绍了一些Qt框架的各种功能和模块,以及如何使用Qt进行GUI开发、网络编程和跨平台应用开发等。实战应用参考资料,源码参考。 适用于初学者和有经验的开发者,能够帮助你快速上手Qt并掌握其...
第3章 Android程序设计基础 3.1 Android程序框架 3.1.1 Android项目目录结构 3.1.2 Android应用解析 3.2 Android的生命周期 3.3 Android程序U设计 3.4 小结 第4章 用户界面开发 4.1 用户界面开发...