使用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文件
<?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);
}
}