okhttp 下载app包

 public void downloadFile() {
		//下载地址
        final String url = HttpClient.baseUrl + "/Public/reception_android/youApp.apk";
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = client.newCall(request);
        Response response = null;
        try {
            response = call.execute();
            //获取下载的内容输入流
            ResponseBody body = response.body();
            InputStream inputStream = body.byteStream();
            final long lengh = body.contentLength();

            // 文件保存到本地
            File file = new File(dir, "youApp.apk");
            FileOutputStream outputStream = new FileOutputStream(file);
            int lien = 0;
            int losing = 0;
            byte[] bytes = new byte[1024];
            while ((lien = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, lien);

                losing += lien;
                final float i = losing * 1.0f / lengh;
                int ii = (int) (i * 100);
                Message msg = handler.obtainMessage();
                msg.arg1 = ii;
                msg.what = 1;
                handler.sendMessage(msg);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //进度条
                progressBar.setProgress(msg.arg1);
                tvLoading.setText("加载进度:" + msg.arg1 + "%");
                if (msg.arg1 == 100) {
                    installAPK();
                }
            }
        }
    };

/**
     * 下载本地后执行安装
     */
    private void installAPK() {
        File apkFile = new File(dir, "youApp.apk");
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", apkFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            Uri uri = Uri.parse("file://" + apkFile.toString());
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        getContext().startActivity(intent);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单的 Android 应用程序下载更新代码的例子,可以帮助你实现应用程序的自动更新。 首先,在你的 Android 项目中添加以下依赖: ```gradle implementation 'com.squareup.okhttp3:okhttp:3.12.12' ``` 然后,创建一个名为 `UpdateManager` 的类,它将处理应用程序的下载和更新: ```java public class UpdateManager { private static final String TAG = "UpdateManager"; private Context mContext; private String mApkUrl; private ProgressDialog mProgressDialog; public UpdateManager(Context context, String apkUrl) { mContext = context; mApkUrl = apkUrl; } public void startUpdate() { showProgressDialog(); downloadApkFile(); } private void showProgressDialog() { mProgressDialog = new ProgressDialog(mContext); mProgressDialog.setMessage("正在下载..."); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.show(); } private void downloadApkFile() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(mApkUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "下载失败: " + e.getMessage()); dismissProgressDialog(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { long totalSize = response.body().contentLength(); long downloadedSize = 0; inputStream = response.body().byteStream(); outputStream = new FileOutputStream(getApkFile()); byte[] buffer = new byte[4096]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); downloadedSize += len; int progress = (int) ((downloadedSize * 100) / totalSize); updateProgressDialog(progress); } outputStream.flush(); Log.i(TAG, "下载完成"); installApk(); } catch (IOException e) { Log.e(TAG, "下载失败: " + e.getMessage()); } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } dismissProgressDialog(); } } }); } private void updateProgressDialog(final int progress) { mProgressDialog.setProgress(progress); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); } } private void installApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(getApkFile()), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } private File getApkFile() { String apkName = mContext.getString(R.string.app_name) + ".apk"; File apkDir = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); return new File(apkDir, apkName); } } ``` 在上面的代码中,`UpdateManager` 类的构造函数需要传入 `Context` 和 APK 下载链接。`startUpdate()` 方法将显示进度对话框和开始下载 APK 文件。下载过程中,我们使用 OkHttp 库来处理网络请求,同时显示下载进度。下载完成后,我们将应用程序安装的文件路径传递给 `installApk()` 方法,以启动安装程序。 你可以在你的应用程序中使用以下代码来调用 `UpdateManager`: ```java UpdateManager updateManager = new UpdateManager(this, "http://yourdomain.com/yourapp.apk"); updateManager.startUpdate(); ``` 请注意,你需要将 APK 下载链接替换为你自己的链接。另外,如果你的应用程序名不同,请确保在 `getApkFile()` 方法中修改应用程序名称。 希望这个例子能够帮助你实现应用程序的自动更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值