Android APP 在线更新 以及适配问题

在线更新思路:
1.申请读写权限
2.获取服务器版本与本地对比
3.需要更新时弹框让用户下载-下载apk(用到读写权限)
4.安卓7.0,8.0适配问题
5.安装

代码简介:
1.读写权限请移步(6.0以上需要动态申请)
不知道的请参考:https://www.jianshu.com/p/af88bf5a3c7b

2.网络请求服务器接口与本地版本对比,本地versionCode和versionName在app下build.gradle中


image.png

获取本地versionName的方法:

 /**
     * 获取versionName
     * @return
     * @throws Exception
     */
    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);
        return packInfo.versionName;
    }

3.下载代码 我把下载的apk文件放在sd卡根目录了

//下载弹框
  protected void showUpdataDialog() {
        AlertDialog.Builder builer = new Builder(context);
        builer.setTitle("版本升级");
        builer.setMessage("检测到新版本,是否升级到新版本");
        //当点确定按钮时从服务器上下载 新的apk 然后安装   װ
        builer.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG, "下载apk,更新");
                downLoadApk();
            }
        });
        builer.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //do sth
            }
        });
        AlertDialog dialog = builer.create();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
 /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    Log.i("hebaodan", "updateurl =="+updateurl);
                    //下载apk
                    file = DownLoadManager.getFileFromServer(updateurl, pd);
                    pd.dismiss(); //结束掉进度条对话框
                    //版本适配和安装
                    checkInstallPermission();

                } catch (Exception e) {
                    pd.dismiss();
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                    Log.i("hebaodan",e.getMessage());
                }
            }}.start();
    }
//下载文件
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后就要安装了
android框架使用StrictMode Api禁止我们的应用对外部(跨越应用分享)公开file://,若使用file://格式共享文件则会报FileUriExposedException异常,android 7.0应用间的文件共享需要使用content://类型的URI分享,并且需要为其提供临时的文件访问权限
(Intent.FLAG_GRANT_READ_URI_PERMISSION和Intent.FLAG_GRANT_WRITE_URI_PERMISSION),对此,官方给我们的建议是使用FileProvider类进行分享
FileProvider使用详情参考:http://www.pianshen.com/article/8970137985/
下面是FileProvider的使用
(1)AndroidManifest.xml文件声明provider

        
        
            
        

(2)在res下新建xml文件夹 ,然后新建一个provider_paths.xml文件
external-path代 表:Environment.getExternalStorageDirectory()
再加上path表示目录为: Environment.getExternalStorageDirectory()+ "/path/"

       

    
    

下面是安装时适配代码

 //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri;
        //判断版本是否是 7.0 及 7.0 以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context,
                    "fd_aidl_client",
                    file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }



        //执行的数据类型
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
        FileUtils.deleteFile(context.getCacheDir()+"/"+ FileUtils.fileName);
    }

(3)7.0适配完后,安卓8.0上安装时又多了一个未知应用安装权限
首先在AndroidManifest.xml中声明安装权限

    
    
    
    
    
    

然后适配7.0前先适配8.0,如果是安卓8.0以上,先跳转到打开权限的页面

//检查位置来源应用权限
public void checkInstallPermission() {
        // 兼容Android 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            //先获取是否有安装未知来源应用的权限
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                // 弹窗,并去设置页面授权
                startInstallPermissionSettingActivity();
            } else {
                installApk();
            }
        } else {
            installApk();
        }
    }
/**
     * 打开未知应用界面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void startInstallPermissionSettingActivity() {

            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builer = new Builder(context);
                    builer.setTitle("权限申请");
                    builer.setMessage("需要打开未知应用安装权限才能完成安装!");
                    //当点确定按钮时从服务器上下载 新的apk 然后安装   װ
                    builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Log.i(TAG, "下载apk,更新");
                            Uri packageURI = Uri.parse("package:" + context.getPackageName());
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                            context.startActivityForResult(intent, MainActivity.REQUEST_INSTALL);
                            dialog.dismiss();
                        }
                    });
                    builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            //do sth
                        }
                    });
                    AlertDialog dialog = builer.create();
                    dialog.setCancelable(false);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }
            });
    }

(4)用户有没有打开权限在activity的onActivityResult中返回

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_INSTALL) {
            Log.i("hebaodan","未知应用安装授权成功");
            updateUtils.installApk();
        } else{
            Log.i("hebaodan","未知应用安装授权失败");
            Toast.makeText(this,"请打开未知应用安装权限",Toast.LENGTH_LONG).show();
        }
    }

5.到此就可以愉快的安装了。安装方法上面以给出

你可能感兴趣的:(Android APP 在线更新 以及适配问题)