版本更新

读写权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

//定义变量

 private final String serverUrl = "http://***.***.247.*7:8**0/goods_file/update_file.json";
    private AlertDialog dialog;
    private Shengji sj;

oncreate方法内

 dialog = new AlertDialog.Builder(ZhuActivity.this).setTitle("有新版本!!!")
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("立刻升级", onclick)
                .setNegativeButton("暂不升级", null).create();

        // 检查是否需要升级
        checkApk();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

方法外

 DialogInterface.OnClickListener onclick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            handler.sendEmptyMessage(1);
        }
    };

定义Handler

Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    sj = (Shengji) msg.obj;
                    dialog.setMessage(sj.description);
                    dialog.show();
                    break;
                case 1:
                xiazai();
            }
        }
    };

// 检查是否需要升级的方法

private void checkApk() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(serverUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    InputStream inputStream = conn.getInputStream();
                    Gson gson = new Gson();

                    Shengji shengji = gson.fromJson(new InputStreamReader(inputStream), Shengji.class);
                    int versionCode = ZhuActivity.this.getPackageManager().getPackageInfo(ZhuActivity.this.getPackageName(), 0).versionCode;
                    if (shengji.version <= versionCode) {
                        Log.i("aaa", "无需升级");
                    } else {
                        Log.i("aaa", "需要升级");
                        Message msg = Message.obtain();
                        msg.obj = shengji;
                        msg.what = 0;
                        handler.sendMessage(msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }.start();

下载新APK

//下载APK
    private void xiazai() {
        final ProgressDialog pd; // 进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(sj.url, pd);
                    sleep(3000);

                    // 安装APk
                    Intent intent = new Intent();
                    // 执行动作
                    intent.setAction(Intent.ACTION_VIEW);
                    // 执行的数据类型
                    intent.setDataAndType(Uri.fromFile(file),
                            "application/vnd.android.package-archive");
                    startActivity(intent);

                    pd.dismiss(); // 结束掉进度条对话框

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

下载中~~~复制进去就行

public 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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值