Download in webview using AsyncTask download (8.0 compatible)
Write a class to inherit Asynctask, and download its file with Httpconnection in doinbackground.
Postexecute is to open the download file (apk) after the download is completed
private class DownloadTask extends AsyncTask<String, Void, Void> { // Pass two parameters: URL and destination path 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; } }
The first parameter is the url. The second parameter is the address downloaded to the mobile phone
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 is used to open apk through 8.0 for installation error. Normally, apk will flash back when it is installed in 8.0 system, so we need to add an xml folder under res, which contains the file [u path. xml file]
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="CacheSqss" path="Sqss"/> </paths>
Add a piece of code to Android manifest, where the attributes of authors are package names
<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>
Finally, I'm sending a piece of ToolUtil tool code, which I also copy from others. It's more convenient for me to use
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) { // hello.text of SD card root return Environment.getExternalStorageDirectory() + "/Sqss"; } else { // The system downloads hello.text from the cache root 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); } /** * Install 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); //Judge whether the version is above 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); } }