1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
| import android.Manifest; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore;
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody;
public class ZFileDownloader {
private static final String TAG = "ZFileDownloader"; private static final int REQUEST_WRITE_PERMISSION = 1001; private static final int BUFFER_SIZE = 8192; private static final int PROGRESS_UPDATE_INTERVAL = 100;
private static volatile OkHttpClient sClient;
@NonNull private static OkHttpClient getClient() { if (sClient == null) { synchronized (ZFileDownloader.class) { if (sClient == null) { sClient = new OkHttpClient.Builder() .build(); } } } return sClient; }
public interface DownloadCallback {
void onSuccess(@Nullable File file);
void onSuccess(@NonNull Uri uri);
void onFailure(@NonNull Exception e);
void onProgress(long bytesRead, long totalBytes); }
public static void downloadFile(@NonNull Activity activity, @NonNull String url, @NonNull String fileName, @Nullable String mimeType, @NonNull DownloadCallback callback) { OkHttpClient client = getClient(); Request request = new Request.Builder() .url(url) .build();
client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { activity.runOnUiThread(() -> callback.onFailure(e)); }
@Override public void onResponse(@NonNull Call call, @NonNull Response response) { if (!response.isSuccessful()) { Exception error = new IOException("Response not successful: " + response.code()); activity.runOnUiThread(() -> callback.onFailure(error)); return; }
ResponseBody body = response.body(); if (body == null) { Exception error = new IOException("Response body is null"); activity.runOnUiThread(() -> callback.onFailure(error)); return; }
long totalBytes = body.contentLength();
try (InputStream inputStream = body.byteStream()) { DownloadResult result = saveFile(activity, inputStream, fileName, mimeType, totalBytes, callback); activity.runOnUiThread(() -> { callback.onSuccess(result.uri); if (result.file != null) { callback.onSuccess(result.file); } }); } catch (Exception e) { activity.runOnUiThread(() -> callback.onFailure(e)); } } }); }
private static class DownloadResult { final Uri uri; final File file;
DownloadResult(@NonNull Uri uri, @Nullable File file) { this.uri = uri; this.file = file; } }
private static DownloadResult saveFile(@NonNull Activity activity, @NonNull InputStream inputStream, @NonNull String fileName, @Nullable String mimeType, long totalBytes, @NonNull DownloadCallback callback) throws IOException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return saveViaMediaStore(activity, inputStream, fileName, mimeType, totalBytes, callback); } else { return saveViaLegacyStorage(activity, inputStream, fileName, totalBytes, callback); } }
private static DownloadResult saveViaMediaStore(@NonNull Activity activity, @NonNull InputStream inputStream, @NonNull String fileName, @Nullable String mimeType, long totalBytes, @NonNull DownloadCallback callback) throws IOException { ContentValues values = new ContentValues(); values.put(MediaStore.Downloads.DISPLAY_NAME, fileName); values.put(MediaStore.Downloads.MIME_TYPE, mimeType != null ? mimeType : "application/octet-stream"); values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
ContentResolver resolver = activity.getContentResolver(); Uri uri = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values); } if (uri == null) { throw new IOException("Failed to create MediaStore entry"); }
try (OutputStream out = resolver.openOutputStream(uri)) { if (out == null) { throw new IOException("Cannot open output stream for Uri: " + uri); } copyStreamWithProgress(inputStream, out, totalBytes, activity, callback); } catch (Exception e) { resolver.delete(uri, null, null); throw e; }
return new DownloadResult(uri, null); }
private static DownloadResult saveViaLegacyStorage(@NonNull Activity activity, @NonNull InputStream inputStream, @NonNull String fileName, long totalBytes, @NonNull DownloadCallback callback) throws IOException { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION); throw new SecurityException("WRITE_EXTERNAL_STORAGE permission denied"); }
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); if (dir != null && !dir.exists()) { dir.mkdirs(); }
File file = new File(dir, fileName); try (FileOutputStream out = new FileOutputStream(file)) { copyStreamWithProgress(inputStream, out, totalBytes, activity, callback); }
return new DownloadResult(Uri.fromFile(file), file); }
private static void copyStreamWithProgress(@NonNull InputStream in, @NonNull OutputStream out, long totalBytes, @NonNull Activity activity, @NonNull DownloadCallback callback) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; long downloaded = 0; int bytesRead; long lastUpdateTime = 0;
while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); downloaded += bytesRead;
long currentTime = System.currentTimeMillis(); if (currentTime - lastUpdateTime >= PROGRESS_UPDATE_INTERVAL) { final long progress = downloaded; activity.runOnUiThread(() -> callback.onProgress(progress, totalBytes)); lastUpdateTime = currentTime; } } out.flush();
final long finalProgress = downloaded; activity.runOnUiThread(() -> callback.onProgress(finalProgress, totalBytes)); } }
|