版本更新

更新管理类

public class UploadManage {
    private Context mcontext;
    private String saveFilePath = "/sdcard/updataApk/";//保存apk到SDcard下面
    private String saveFileNmae = saveFilePath + "apkName.apk";//下载完成的文件名字
    private boolean canceFlag = false;//停止下载的标记
    AlertDialog alertDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    installApkFile(mcontext,saveFilePath);
                    break;
                case 2:
                    //更新进度条

                    break;
            }
        }
    };

    public void showDialog(final UploadAppBean.ResultBean resultBean) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mcontext);
        dialog.setTitle("发现新版本" + resultBean.getVersionName());
        dialog.setMessage(resultBean.getDesc());
        dialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                downloadApk(resultBean.getApkUrl());
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (resultBean.isFlag()) {
                    //关闭
                    Toast.makeText(mcontext, "close", Toast.LENGTH_SHORT).show();
                } else {
                    dialogInterface.dismiss();
                }
            }
        });
        dialog.create().show();
    }


    public UploadManage(Context context) {
        this.mcontext = context;
    }

    //下载apk
    public void downloadApk(final String apkUrl) {
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    int length = connection.getContentLength();
                    InputStream is = connection.getInputStream();
                    File file = new File(saveFilePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String apkFile = saveFileNmae;
                    File file1 = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(file1);
                    int count = 0;
                    byte[] bytes = new byte[1024];
                    int l = 0;
                    while ((l = is.read(bytes)) != -1) {
                        count += l;
                        fos.write(bytes, 0, l);
                        fos.flush();
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                    handler.sendEmptyMessage(1);
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    //安装apk 的方法
    public static void installApkFile(Context context ,String mSavePath) {

        Log.d("cx","+++++++++++++++++++");
        File apkfile = new File(mSavePath, "apkName.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (!apkfile.exists()) {
            return;
        }
//判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                String ss = "com.example.updataapp" + ".fileprovider";
                Uri contentUri = FileProvider.getUriForFile(context.getApplicationContext(), ss, apkfile);
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    //获取当前版本号
    public long getAppVersionCode() {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = mcontext.getApplicationContext().getPackageManager().getPackageInfo(mcontext.getPackageName(), 0);
            appVersionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionCode;
    }

    //获取当前的版本名称
    public String getAppVersionName() {
        String appVersionName = "";

        try {
            PackageInfo packageInfo = mcontext.getApplicationContext().getPackageManager().getPackageInfo(mcontext.getPackageName(), 0);
            appVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionName;

    }
}

application标签下 添加provider

 <provider
            android:name="androidx.core.content.FileProvider"
            //路径 --包名+fileprovider
            android:authorities="com.example.updataapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false"
            >
            <meta-data
            // FileProvider 中  --private static final String META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
                android:name="android.support.FILE_PROVIDER_PATHS"
                //xml文件
                android:resource="@xml/file_paths" />
        </provider>

新建res文件 下的 xml

<paths>
    <!--   path="com.example.updataapp"== 包名  -->
    <external-path
        name="files_root"
        path="com.example.updataapp" />
    <!-- path="." == 所有路径    name="apkName.apk"==  安装的名称                          -->
    <external-path
        name="apkName.apk"
        path="." />
</paths>

判断更新

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UploadAppBean.ResultBean resultBean = setUpload();
        uploadCode(resultBean);
        //动态权限
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    "android.permission.WRITE_EXTERNAL_STORAGE",
                    "android.permission.READ_EXTERNAL_STORAGE"

            }, 100);

        }
    }
    public void uploadCode(UploadAppBean.ResultBean resultBean) {
    
        UploadManage uploadManage = new UploadManage(this);
        long code = uploadManage.getAppVersionCode();
        String name = uploadManage.getAppVersionName();
        if (code < resultBean.getVersionCode()) {//需要更新
            uploadManage.showDialog(resultBean);
        }
      
    }

    public UploadAppBean.ResultBean setUpload() {
    //更新的bean类
        UploadAppBean.ResultBean resultBean = new UploadAppBean.ResultBean();
        //版本
        resultBean.setVersionCode(250);
        resultBean.setVersionName("2.5.0");
        //下载的路径
        resultBean.setApkUrl("http://10.161.9.95/upload/app-release.apk");
        //更新的内容
        resultBean.setDesc("1.修改了bug,2.更新了我的页面手势解锁,3.添加了新品页面");
        //强制更新
        resultBean.setFlag(true);
        return resultBean;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值