主要原理是:
在应用启动的时候,去取服务器上版本号 ,与当前应用的对比如果有更新则下载
下面这个是获取当前应用的版本信息
private void getCurVersion() { try { PackageInfo pInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); curVersion = pInfo.versionName; curVersionCode = pInfo.versionCode; } catch (NameNotFoundException e) { Log.e("update", e.getMessage()); curVersion = "1.0.1"; curVersionCode = 1; } }
服务器端格式如下 version_1.0.2
HttpURLConnection 获取输入流,再用
BufferedReader 缓冲流,readline成String,再比较
private boolean check_update(){ String getstring = null; String version=null; getCurVersion(); try { URL myurl=new URL(app_check); HttpURLConnection urlconnection=(HttpURLConnection) myurl.openConnection(); urlconnection.setReadTimeout(50000); urlconnection.setConnectTimeout(50000); urlconnection.connect(); InputStream in=urlconnection.getInputStream(); BufferedReader buffread; buffread=new BufferedReader(new InputStreamReader(in,"utf-8")); String line; line=buffread.readLine(); while(line!=null){ getstring+=line; line=buffread.readLine(); } int index=getstring.indexOf("version_"); //2.0.1 version=getstring.substring(index+8, index+13); in.close(); Log.e("version",version); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(version!=null){ if(version.compareTo(curVersion)>0) return true; else return false; } else return false; }
private void showdownDialog(){ AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle("软件版本更新"); dialog.setMessage("有最新的app更新"); dialog.setNegativeButton("以后再说", new OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub arg0.dismiss(); } }); dialog.setPositiveButton("确定", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub //确定里面调用下载线程,同时显示下载的那个进度对话框 dialog.dismiss(); cancel=true; downapk(); showDownapk(); } }); dialog.show(); }
private void setInstall(){
File apkfile = new File(apk_path);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
context.startActivity(i);
}
android 自动更新的实现,布布扣,bubuko.com
原文:http://blog.csdn.net/a11123939/article/details/27978753