android版本更新(获取版本信息)

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;
    }
View Code

 

.获取服务器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"/>
View Code

2.服务器上txt文件形式

#version.txt
{"code":"2.0","update":"http://hnzldzkj.cn/static/apks/version.txt"}  
View Code

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();
    }
View Code

 

三.比较本地apk和服务器上apk的版本号(versionCode)

if(new_apkcode>getVersionCode(getContext())){    //如果新版本的versionCode大于旧版本的
                    showUpdataDialog();
                }else {
                    Toast.makeText(getActivity(),"当前为最新版本!",Toast.LENGTH_SHORT).show();
                }
View Code

 

四.下载安装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();//显示对话框
    }
View Code

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();
    }
View Code

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;
        }
    }
View Code

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);
    }
View Code

 

转载于:https://www.cnblogs.com/gaoyukun/p/10318099.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio 中实现应用程序版本更新,一般可以通过以下步骤进行: 1. 在应用程序的后端服务器上创建一个文件,用于存放最新版本apk 文件的下载链接以及版本号等信息。 2. 在应用程序中添加一个检查更新的功能,当用户打开应用程序时,通过与后端服务器交互,检查当前版本是否为最新版本。 3. 如果不是最新版本,则提示用户更新。此时可以采用两种方式: ① 弹出对话框提示用户更新,如果用户点击“确定”按钮,则跳转到下载最新版 apk 文件的页面,让用户下载安装最新版的应用程序。 ② 直接下载最新版 apk 文件,并提示用户安装。此方法需要先在 AndroidManifest.xml 文件中添加下载权限。 以下是一些参考代码: ```java // 检查应用程序是否有新版本 private void checkUpdate() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://your-backend-server.com/version.json").build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 请求失败 } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); // 解析 json 文件,获取最新版本号以及 apk 文件下载链接等信息 if (needUpdate) { // 提示用户更新 runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("发现新版本"); builder.setMessage("是否立即更新?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 跳转到下载最新版 apk 文件的页面 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(apkUrl)); startActivity(intent); } }); builder.setNegativeButton("取消", null); builder.show(); } }); } } }); } ``` 如果选择直接下载最新版 apk 文件的方式,可以参考以下代码: ```java private void downloadApk() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(apkUrl).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败 } @Override public void onResponse(Call call, Response response) throws IOException { InputStream inputStream = response.body().byteStream(); FileOutputStream fos = null; try { File file = new File(getExternalFilesDir(null), "app.apk"); fos = new FileOutputStream(file); byte[] buffer = new byte[2048]; int len; while ((len = inputStream.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.flush(); // 安装应用程序 installApk(file); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { inputStream.close(); } if (fos != null) { fos.close(); } } } }); } private void installApk(File file) { Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Uri uriForFile = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(uriForFile, "application/vnd.android.package-archive"); } else { intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } ``` 以上代码仅供参考,具体实现方式还需根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值