使用AsyncTask下载在webview中下载(8.0兼容)

使用AsyncTask下载在webview中下载(8.0兼容)
先写一个类 继承Asynctask,在doinbackground中用Httpconnection下载其文件。
Postexecute是其下载完成后进行打开下载文件(apk的操作)

 private class DownloadTask extends AsyncTask<String, Void, Void> {
        // 传递两个参数:URL 和 目标路径
        private String url;
        private String destPath;

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(String... params) {

            url = params[0];
            destPath = params[1];
            OutputStream out = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(15000);
                urlConnection.setReadTimeout(15000);
                InputStream in = urlConnection.getInputStream();
                out = new FileOutputStream(params[1]);
                byte[] buffer = new byte[10 * 1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                in.close();
            } catch (IOException e) {

            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {

                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24)
            {

                String mimeType = getMIMEType(url);
                FileProvider.getUriForFile(MainActivity.this,"gonglue.zhuayou.com",new File(destPath));
                Uri uri = Uri.fromFile(new File(destPath));
                handlerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                handlerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                handlerIntent.setDataAndType(uri, mimeType);
            }else
                {
                    String mimeType = getMIMEType(url);
                    Uri uri = Uri.fromFile(new File(destPath));
                    handlerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    handlerIntent.setDataAndType(uri, mimeType);
                }

            startActivity(handlerIntent);
        }
    }

    private String getMIMEType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);

        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }
}

其使用方法是 第一个参数我们传入 url 第二个参数为下载到手机的地址

web.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
                String destPath = ToolsUtil.getApkDir()+ fileName;
                new DownloadTask().execute(url,destPath);


            }
        });

ToolUtil是用来过8.0打开apk安装错误的。正常apk在8.0 系统安装时会闪退 于是我们在res下加一个xml文件夹,里面加上file_path.xml文件filepath

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

在AndroidManifest中添加一段代码其中authorities的属性是包名

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="gonglue.zhuayou.com"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
        </provider>

最后在发一段ToolUtil工具代码 我也是从别人那边copy的 比较方便 我都是这么用的

package gonglue.zhuayou.com.myapplication;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

/**
 * Created by Administrator on 2018\4\24 0024.
 */

public class ToolsUtil {
    private static boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

    private static String getAppDir() {

        if (hasSDCard) { // SD卡根目录的hello.text
            return Environment.getExternalStorageDirectory() + "/Sqss";
        } else {  // 系统下载缓存根目录的hello.text
            return Environment.getDownloadCacheDirectory() + "/Sqss";
        }
    }

    private static String mkdirs(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dir;
    }

    public static String getApkDir() {
        String dir = getAppDir() + "/apk/";
        return mkdirs(dir);
    }
    /**
     * 安装APK
     *
     * @param context
     * @param apkPath
     */
    public static void installApk(Context context, String apkPath) {
        if (context == null || TextUtils.isEmpty(apkPath)) {
            return;
        }
        File file = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, "com.example.administrator.myapplication", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值