主要原理是:
在应用启动的时候,去取服务器上版本号 ,与当前应用的对比如果有更新则下载
下面这个是获取当前应用的版本信息
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; } }
下面则是通过java net包来get版本信息,进行比较
服务器端格式如下 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(); }
最后则是发出一个Intent广播
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 自动更新的实现
时间: 2024-10-27 11:18:47