The main principle is:
When the application is started, the version number on the server is retrieved. If the application is updated, the version number is downloaded.
The following shows how to obtain the version information of the current application.
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; } }
The following is a comparison of get version information through the java net package.
The server format is as follows: version_1.0.2
HttpURLConnection gets the input stream, and then
BufferedReader buffer the stream, readline into String, and then compare
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.1version=getstring.substring(index+8, index+13);in.close();Log.e("version",version);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} if(version!=null){if(version.compareTo(curVersion)>0)return true;elsereturn false; } else return false;}
Next, a dialog box is displayed and the download thread is called.
Private void showdownDialog () {AlertDialog. builder dialog = new AlertDialog. builder (context); dialog. setTitle ("Software Version Update"); dialog. setMessage ("updated with the latest app"); dialog. setNegativeButton ("later", new OnClickListener () {@ Overridepublic void onClick (DialogInterface arg0, int arg1) {// TODO Auto-generated method stubarg0.dismiss ();}}); dialog. setPositiveButton ("OK", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stub // confirm that the download thread is called, at the same time, the download progress dialog box dialog is displayed. dismiss (); cancel = true; downapk (); showDownapk () ;}}); dialog. show ();}
Finally, an Intent broadcast is sent.
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 );
}