Android 版本升级

在应用中, 版本升级是每个应用都需要做的功能, 下面介绍下主要代码.

首先每次进入应用判断版本号与后台设置是否一致, 不一致即提示用户升级更新.为适配Android6.0加入运行时权限. 添加代码
    if (ContextCompat.checkSelfPermission(MainActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                        } else {
                        //这里表示以允许写入权限,  
                        //这里写下载apk的代码
                        }

如果检测为开通权限, 则会出提示框提示开通, 回调的代码

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          //这里写下载apk的代码
        }

    }

下面是如何下载apk

private NotificationManager notificationManager;
private Notification notification;
RemoteViews view = null;

private void downloadApk(final String url) {
        new EasyLocalTask<Void, File>() {

            @Override
            protected File doInBackground(Void... params) {
                File file = new File(CheLiWangApp.CACHE_ROOT_CACHE_DIR + File.separator + CheLiWangConfig.APK_NAME);
                try {
                    LogUtil.e(url);
                    notification();

                    HttpUtil.downloadFile(url, file, new HttpUtil.IDownloadCallback() {

                        int i = 0;

                        @Override
                        public void onProgress(long currentSize, long totalSize) {

                            progress = (int) (((float) currentSize / totalSize) * 100);

                            if ((int) (progress / 10) > i) {
                                i = (int) (progress / 10);
                                // 更改进度条
                                notification.contentView.setProgressBar(R.id.progress, (int) (totalSize / 1024 / 1000),
                                        (int) (currentSize / 1024 / 1000), false);
                                // 发送消息
                                notificationManager.notify(101, notification);
                            }
                        }
                    });
                    // HttpUtil.downloadFile(url, file);
                } catch (IOException e) {
                    file = null;
                }

                return file;
            }

            @Override
            protected void onPostExecute(File result) {
                super.onPostExecute(result);
                if (result != null) {
                    notificationManager.cancel(101);// notification关闭不显示
                    install(MainActivity.this, result);
                }
            }
        }.execute();
    }


 private void notification() {
      notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      notification = new Notification(R.drawable.ic_launcher, "下载新版本", System.currentTimeMillis());

        if (view == null) {
            view = new RemoteViews(getPackageName(), R.layout.notification);
            notification.contentView = view;
            notification.contentView.setProgressBar(R.id.progress, 100, 0, false);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(this, R.string.app_name, new Intent(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.contentIntent = contentIntent;
        notification.flags |= Notification.FLAG_ONGOING_EVENT;// 滑动或者clear都不会清空

        notificationManager.notify(101, notification);
    }

下面是安装apk的代码, 适配Android7.0, 解决7.0安装下载好的apk闪退bug
首先需在manifest中application 中加上

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.clwapp.test.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <!--元数据-->
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

并在res目录下新建文件夹xml文件夹, 创建file_paths.xml文件
写入代码

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <external-path
            name="download"
            path=""/>
    </paths>
</resources>

在MainActivity 中调用安装方法

public void install(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context, "com.clwapp.test.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值