android 更新实现自己主动

it2025-09-08  102

其主要原理是:

在应用程序启动。取server在版本 ,

以下这个是获取当前应用的版本号信息

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版本号信息。进行比較

server端格式例如以下     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); }

版权声明:本文博客原创文章,博客,未经同意,不得转载。

转载于:https://www.cnblogs.com/bhlsheji/p/4632260.html

最新回复(0)