apk更新前请注意:在每次更新apk只需要递增versionCode即可,新版本的versionCode必须要比旧版本的大,versionName只是给用户看的。
一.获取本地apk版本信息(对应程序中build.gradle中的versionCode,versionName)

/* * 获取当前程序的版本号 */ public static int getVersionCode(Context mContext) { int versionCode = 0; try { //获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode = mContext.getPackageManager(). getPackageInfo(mContext.getPackageName(), 0).versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } //获取版本号名称(对应versionName) public static String getVerName(Context context) { String verName = ""; try { verName = context.getPackageManager(). getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return verName; }
二.获取服务器apk版本信息(说白了就是在服务器写一个json或txt文件,里面标识着版本信息,鄙人才疏学浅,目前还不能直接获取上传至服务器apk内的版本信息)
1.添加网络访问权限

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!--下载文件读写权限--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.服务器上txt文件形式

#version.txt {"code":"2.0","update":"http://hnzldzkj.cn/static/apks/version.txt"}
3.访问服务器txt文件并解析字段代码(需在线程中调用)

private String getVersion() throws IOException, JSONException { URL url = new URL("http://hnzldzkj.cn/static/apks/version.txt"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setReadTimeout(8 * 1000); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String string; string = bufferedReader.readLine(); //对json数据进行解析 JSONObject jsonObject = new JSONObject(string); String strings = jsonObject.getString("code"); return strings; } //在线程中调用(a为全局变量 ps可设可不设(自己看情况,调用即可)) private void thread_start(){ new Thread(new Runnable() { @Override public void run() { try { a=getVersion(); }catch (Exception e){ } } }).start(); }
三.比较本地apk和服务器上apk的版本号(versionCode)

if(new_apkcode>getVersionCode(getContext())){ //如果新版本的versionCode大于旧版本的 showUpdataDialog(); }else { Toast.makeText(getActivity(),"当前为最新版本!",Toast.LENGTH_SHORT).show(); }
四.下载安装apk
1.弹出对话框

protected void showUpdataDialog() { AlertDialog dialog = new AlertDialog.Builder(getContext()).create();//创建对话框 dialog.setIcon(R.mipmap.titles);//设置对话框icon dialog.setTitle("版本升级");//设置对话框标题 dialog.setMessage("软件更新");//设置文字显示内容 //分别设置三个button dialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { downLoadApk(); } }); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss();//关闭对话框 } }); dialog.show();//显示对话框 }
2.设置进度条

protected void downLoadApk() { //进度条 final ProgressDialog pd; pd = new ProgressDialog(getContext()); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("正在下载更新"); pd.show(); new Thread(){ @Override public void run() { try { File file = getFileFromServer("http://hnzldzkj.cn/static/apks/采集大师.apk", pd); //安装APK installApk(file); pd.dismiss(); //结束掉进度条对话框 } catch (Exception e) { } }}.start(); }
3.下载apk

public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{ //如果相等的话表示当前的sdcard挂载在手机上并且是可用的 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); //获取到文件的大小 pd.setMax(conn.getContentLength()); InputStream is = conn.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(), "updata.apk"); FileOutputStream fos = new FileOutputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] buffer = new byte[1024]; int len ; int total=0; while((len =bis.read(buffer))!=-1){ fos.write(buffer, 0, len); total+= len; //获取当前下载量 pd.setProgress(total); } fos.close(); bis.close(); is.close(); return file; } else{ return null; } }
4.安装apk

protected void installApk(File file) { Intent intent = new Intent(); //执行动作 intent.setAction(Intent.ACTION_VIEW); //执行的数据类型 intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); }