blob: f42ee7681160ba50074e124f8ad06af093c7f165 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Bijan Amirzada41242f22014-03-21 12:12:18 -070017package com.android.browser;
Michael Kolb8233fac2010-10-26 16:08:53 -070018
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.DownloadManager;
luxiaol62677b02013-07-22 07:54:49 +080022import android.app.DownloadManager.Request;
Michael Kolb8233fac2010-10-26 16:08:53 -070023import android.content.ActivityNotFoundException;
24import android.content.ComponentName;
Michael Kolb8233fac2010-10-26 16:08:53 -070025import android.content.Context;
qqzhoua95a2e22013-04-18 17:28:31 +080026import android.content.DialogInterface;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.Intent;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
30import android.net.Uri;
luxiaol62677b02013-07-22 07:54:49 +080031import android.os.Bundle;
Michael Kolb8233fac2010-10-26 16:08:53 -070032import android.os.Environment;
luxiaol62677b02013-07-22 07:54:49 +080033import android.os.StatFs;
34import android.os.storage.StorageManager;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.util.Log;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080036import org.codeaurora.swe.CookieManager;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.webkit.URLUtil;
38import android.widget.Toast;
39
Bijan Amirzada41242f22014-03-21 12:12:18 -070040import com.android.browser.R;
41import com.android.browser.platformsupport.WebAddress;
42import com.android.browser.reflect.ReflectHelper;
luxiaol62677b02013-07-22 07:54:49 +080043
Axesh R. Ajmera2e241242014-05-19 15:53:38 -070044import java.util.regex.Matcher;
45import java.util.regex.Pattern;
46
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080047import java.io.File;
Michael Kolb8233fac2010-10-26 16:08:53 -070048/**
49 * Handle download requests
50 */
51public class DownloadHandler {
52
53 private static final boolean LOGD_ENABLED =
Bijan Amirzada41242f22014-03-21 12:12:18 -070054 com.android.browser.Browser.LOGD_ENABLED;
Michael Kolb8233fac2010-10-26 16:08:53 -070055
56 private static final String LOGTAG = "DLHandler";
luxiaol62677b02013-07-22 07:54:49 +080057 private static String mInternalStorage;
58 private static String mExternalStorage;
59 private final static String INVALID_PATH = "/storage";
Michael Kolb8233fac2010-10-26 16:08:53 -070060
luxiaol62677b02013-07-22 07:54:49 +080061 public static void startingDownload(Activity activity,
62 String url, String userAgent, String contentDisposition,
63 String mimetype, String referer, boolean privateBrowsing, long contentLength,
64 String filename, String downloadPath) {
65 // java.net.URI is a lot stricter than KURL so we have to encode some
66 // extra characters. Fix for b 2538060 and b 1634719
67 WebAddress webAddress;
68 try {
69 webAddress = new WebAddress(url);
70 webAddress.setPath(encodePath(webAddress.getPath()));
71 } catch (Exception e) {
72 // This only happens for very bad urls, we want to chatch the
73 // exception here
74 Log.e(LOGTAG, "Exception trying to parse url:" + url);
75 return;
76 }
77
78 String addressString = webAddress.toString();
79 Uri uri = Uri.parse(addressString);
80 final DownloadManager.Request request;
81 try {
82 request = new DownloadManager.Request(uri);
83 } catch (IllegalArgumentException e) {
84 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
85 return;
86 }
87 request.setMimeType(mimetype);
88 // set downloaded file destination to /sdcard/Download.
89 // or, should it be set to one of several Environment.DIRECTORY* dirs
90 // depending on mimetype?
91 try {
92 setDestinationDir(downloadPath, filename, request);
93 } catch (Exception e) {
94 showNoEnoughMemoryDialog(activity);
95 return;
96 }
97 // let this downloaded file be scanned by MediaScanner - so that it can
98 // show up in Gallery app, for example.
99 request.allowScanningByMediaScanner();
100 request.setDescription(webAddress.getHost());
101 // XXX: Have to use the old url since the cookies were stored using the
102 // old percent-encoded url.
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800103
luxiaol62677b02013-07-22 07:54:49 +0800104 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
105 request.addRequestHeader("cookie", cookies);
106 request.addRequestHeader("User-Agent", userAgent);
107 request.addRequestHeader("Referer", referer);
Panos Thomase57e3a02014-04-30 20:25:16 -0700108 request.setVisibleInDownloadsUi(!privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800109 request.setNotificationVisibility(
110 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
111 final DownloadManager manager = (DownloadManager) activity
112 .getSystemService(Context.DOWNLOAD_SERVICE);
113 new Thread("Browser download") {
114 public void run() {
115 manager.enqueue(request);
116 }
117 }.start();
Panos Thomase57e3a02014-04-30 20:25:16 -0700118 showStartDownloadToast(activity, privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800119 }
120
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800121 private static boolean isAudioFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700122 Object[] params = {Integer.valueOf(fileType)};
123 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700124 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700125 "isAudioFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800126 return result;
127 }
128
129 private static boolean isVideoFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700130 Object[] params = {Integer.valueOf(fileType)};
131 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700132 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700133 "isVideoFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800134 return result;
135 }
136
kaiyize6a27d02013-08-22 15:08:19 +0800137 /**
138 * Notify the host application a download should be done, or that
139 * the data should be streamed if a streaming viewer is available.
140 * @param activity Activity requesting the download.
141 * @param url The full url to the content that should be downloaded
142 * @param userAgent User agent of the downloading application.
143 * @param contentDisposition Content-disposition http header, if present.
144 * @param mimetype The mimetype of the content reported by the server
145 * @param referer The referer associated with the downloaded url
146 * @param privateBrowsing If the request is coming from a private browsing tab.
147 */
qqzhoua95a2e22013-04-18 17:28:31 +0800148 public static boolean onDownloadStart(final Activity activity, final String url,
149 final String userAgent, final String contentDisposition, final String mimetype,
luxiaol62677b02013-07-22 07:54:49 +0800150 final String referer, final boolean privateBrowsing, final long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 // if we're dealing wih A/V content that's not explicitly marked
152 // for download, check if it's streamable.
153 if (contentDisposition == null
154 || !contentDisposition.regionMatches(
155 true, 0, "attachment", 0, 10)) {
qqzhoua95a2e22013-04-18 17:28:31 +0800156 // Add for Carrier Feature - When open an audio/video link, prompt a dialog
157 // to let the user choose play or download operation.
158 Uri uri = Uri.parse(url);
159 String scheme = uri.getScheme();
160 Log.v(LOGTAG, "scheme:" + scheme + ", mimetype:" + mimetype);
161 // Some mimetype for audio/video files is not started with "audio" or "video",
162 // such as ogg audio file with mimetype "application/ogg". So we also check
163 // file type by MediaFile.isAudioFileType() and MediaFile.isVideoFileType().
164 // For those file types other than audio or video, download it immediately.
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700165 Object[] params = {mimetype};
166 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700167 Integer result = (Integer) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700168 "getFileTypeForMimeType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800169 int fileType = result.intValue();
qqzhoua95a2e22013-04-18 17:28:31 +0800170 if ("http".equalsIgnoreCase(scheme) &&
171 (mimetype.startsWith("audio/") ||
172 mimetype.startsWith("video/") ||
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800173 isAudioFileType(fileType) ||
174 isVideoFileType(fileType))) {
qqzhoua95a2e22013-04-18 17:28:31 +0800175 new AlertDialog.Builder(activity)
176 .setTitle(R.string.application_name)
177 .setIcon(R.drawable.default_video_poster)
178 .setMessage(R.string.http_video_msg)
179 .setPositiveButton(R.string.video_save, new DialogInterface.OnClickListener() {
180 public void onClick(DialogInterface dialog, int which) {
181 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800182 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800183 }
184 })
185 .setNegativeButton(R.string.video_play, new DialogInterface.OnClickListener() {
186 public void onClick(DialogInterface dialog, int which) {
187 Intent intent = new Intent(Intent.ACTION_VIEW);
188 intent.setDataAndType(Uri.parse(url), mimetype);
189 try {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700190 String trimmedcontentDisposition = trimContentDisposition(contentDisposition);
191 String title = URLUtil.guessFileName(url, trimmedcontentDisposition, mimetype);
qqzhoua95a2e22013-04-18 17:28:31 +0800192 intent.putExtra(Intent.EXTRA_TITLE, title);
193 activity.startActivity(intent);
194 } catch (ActivityNotFoundException ex) {
195 Log.w(LOGTAG, "When http stream play, activity not found for "
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700196 + mimetype + " over " + Uri.parse(url).getScheme(), ex);
qqzhoua95a2e22013-04-18 17:28:31 +0800197 }
198 }
199 }).show();
200
201 return true;
202 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700203 // query the package manager to see if there's a registered handler
204 // that matches.
205 Intent intent = new Intent(Intent.ACTION_VIEW);
206 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500207 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700208 PackageManager.MATCH_DEFAULT_ONLY);
209 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500210 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700211 // If we resolved to ourselves, we don't want to attempt to
212 // load the url only to try and download it again.
213 if (!myName.getPackageName().equals(
214 info.activityInfo.packageName)
215 || !myName.getClassName().equals(
216 info.activityInfo.name)) {
217 // someone (other than us) knows how to handle this mime
218 // type with this scheme, don't download.
219 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500220 activity.startActivity(intent);
qqzhoua95a2e22013-04-18 17:28:31 +0800221 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 } catch (ActivityNotFoundException ex) {
223 if (LOGD_ENABLED) {
224 Log.d(LOGTAG, "activity not found for " + mimetype
225 + " over " + Uri.parse(url).getScheme(),
226 ex);
227 }
228 // Best behavior is to fall back to a download in this
229 // case
230 }
231 }
232 }
233 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500234 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800235 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800236 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700237 }
238
239 // This is to work around the fact that java.net.URI throws Exceptions
240 // instead of just encoding URL's properly
241 // Helper method for onDownloadStartNoStream
242 private static String encodePath(String path) {
243 char[] chars = path.toCharArray();
244
245 boolean needed = false;
246 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700247 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700248 needed = true;
249 break;
250 }
251 }
252 if (needed == false) {
253 return path;
254 }
255
256 StringBuilder sb = new StringBuilder("");
257 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700258 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700259 sb.append('%');
260 sb.append(Integer.toHexString(c));
261 } else {
262 sb.append(c);
263 }
264 }
265
266 return sb.toString();
267 }
268
269 /**
270 * Notify the host application a download should be done, even if there
271 * is a streaming viewer available for thise type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500272 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700273 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500274 * @param userAgent User agent of the downloading application.
275 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700276 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700277 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000278 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700279 */
luxiaol62677b02013-07-22 07:54:49 +0800280 /* package */static void onDownloadStartNoStream(Activity activity,
Leon Scroggins63c02662010-11-18 15:16:27 -0500281 String url, String userAgent, String contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800282 String mimetype, String referer, boolean privateBrowsing, long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700283
luxiaol62677b02013-07-22 07:54:49 +0800284 initStorageDefaultPath(activity);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700285
286 contentDisposition = trimContentDisposition(contentDisposition);
287
Michael Kolb8233fac2010-10-26 16:08:53 -0700288 String filename = URLUtil.guessFileName(url,
289 contentDisposition, mimetype);
290
291 // Check to see if we have an SDCard
292 String status = Environment.getExternalStorageState();
293 if (!status.equals(Environment.MEDIA_MOUNTED)) {
294 int title;
295 String msg;
296
297 // Check to see if the SDCard is busy, same as the music app
298 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500299 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700300 title = R.string.download_sdcard_busy_dlg_title;
301 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500302 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 title = R.string.download_no_sdcard_dlg_title;
304 }
305
Leon Scroggins63c02662010-11-18 15:16:27 -0500306 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700307 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200308 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700309 .setMessage(msg)
310 .setPositiveButton(R.string.ok, null)
311 .show();
312 return;
313 }
314
Michael Kolb8233fac2010-10-26 16:08:53 -0700315 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700316 // We must have long pressed on a link or image to download it. We
317 // are not sure of the mimetype in this case, so do a head request
luxiaol62677b02013-07-22 07:54:49 +0800318 new FetchUrlMimeType(activity, url, userAgent, referer,
319 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700320 } else {
luxiaol62677b02013-07-22 07:54:49 +0800321 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
322 privateBrowsing, contentLength, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700323 }
luxiaol62677b02013-07-22 07:54:49 +0800324
325 }
326
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700327 static String trimContentDisposition(String contentDisposition) {
328 final Pattern CONTENT_DISPOSITION_PATTERN =
329 Pattern.compile("attachment;\\s*filename\\s*=\\s*(\"?)([^\"]*)\\1\\s*;",
330 Pattern.CASE_INSENSITIVE);
331
332 if (contentDisposition != null) {
333
334 try {
335 Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
336 if (m.find()) {
337 return m.group();
338 } else {
339 return contentDisposition;
340 }
341 } catch (IllegalStateException ex) {
342 // This function is defined as returning null when it can't parse the header
343 }
344 }
345 return null;
346 }
347
luxiaol62677b02013-07-22 07:54:49 +0800348 public static void initStorageDefaultPath(Context context) {
349 mExternalStorage = getExternalStorageDirectory(context);
350 if (isPhoneStorageSupported()) {
351 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
352 } else {
353 mInternalStorage = null;
354 }
355 }
356
357 public static void startDownloadSettings(Activity activity,
358 String url, String userAgent, String contentDisposition,
359 String mimetype, String referer, boolean privateBrowsing, long contentLength,
360 String filename) {
361 Bundle fileInfo = new Bundle();
362 fileInfo.putString("url", url);
363 fileInfo.putString("userAgent", userAgent);
364 fileInfo.putString("contentDisposition", contentDisposition);
365 fileInfo.putString("mimetype", mimetype);
366 fileInfo.putString("referer", referer);
367 fileInfo.putLong("contentLength", contentLength);
368 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
369 fileInfo.putString("filename", filename);
370 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
371 intent.putExtras(fileInfo);
372 activity.startActivity(intent);
373 }
374
375 public static void setAppointedFolder(String downloadPath) {
376 File file = new File(downloadPath);
377 if (file.exists()) {
378 if (!file.isDirectory()) {
379 throw new IllegalStateException(file.getAbsolutePath() +
380 " already exists and is not a directory");
381 }
382 } else {
383 if (!file.mkdir()) {
384 throw new IllegalStateException("Unable to create directory: " +
385 file.getAbsolutePath());
386 }
387 }
388 }
389
390 private static void setDestinationDir(String downloadPath, String filename, Request request) {
391 File file = new File(downloadPath);
392 if (file.exists()) {
393 if (!file.isDirectory()) {
394 throw new IllegalStateException(file.getAbsolutePath() +
395 " already exists and is not a directory");
396 }
397 } else {
398 if (!file.mkdir()) {
399 throw new IllegalStateException("Unable to create directory: " +
400 file.getAbsolutePath());
401 }
402 }
403 setDestinationFromBase(file, filename, request);
404 }
405
406 private static void setDestinationFromBase(File file, String filename, Request request) {
407 if (filename == null) {
408 throw new NullPointerException("filename cannot be null");
409 }
410 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
411 }
412
413 public static void fileExistQueryDialog(Activity activity) {
414 new AlertDialog.Builder(activity)
415 .setTitle(R.string.download_file_exist)
416 .setIcon(android.R.drawable.ic_dialog_info)
417 .setMessage(R.string.download_file_exist_msg)
418 // if yes, delete existed file and start new download thread
419 .setPositiveButton(R.string.ok, null)
420 // if no, do nothing at all
421 .show();
422 }
423
424 public static long getAvailableMemory(String root) {
425 StatFs stat = new StatFs(root);
426 final long LEFT10MByte = 2560;
427 long blockSize = stat.getBlockSize();
428 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
429 return availableBlocks * blockSize;
430 }
431
432 public static void showNoEnoughMemoryDialog(Activity mContext) {
433 new AlertDialog.Builder(mContext)
434 .setTitle(R.string.download_no_enough_memory)
435 .setIconAttribute(android.R.attr.alertDialogIcon)
436 .setMessage(R.string.download_no_enough_memory)
437 .setPositiveButton(R.string.ok, null)
438 .show();
439 }
440
kaiyize6a27d02013-08-22 15:08:19 +0800441 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800442 long mAvailableBytes = getAvailableMemory(root);
443 if (mAvailableBytes > 0) {
444 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800445 return true;
446 }
447 } else {
luxiaol62677b02013-07-22 07:54:49 +0800448 return true;
449 }
450 return false;
451 }
452
Panos Thomase57e3a02014-04-30 20:25:16 -0700453 public static void showStartDownloadToast(Activity activity,
454 boolean privateBrowsing) {
455 if (!privateBrowsing) {
456 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
457 activity.startActivity(intent);
458 } else {
459 activity.finish();
460 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500461 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700462 .show();
463 }
464
luxiaol62677b02013-07-22 07:54:49 +0800465 /**
466 * wheather the storage status OK for download file
467 *
468 * @param activity
469 * @param filename the download file's name
470 * @param downloadPath the download file's path will be in
471 * @return boolean true is ok,and false is not
472 */
473 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
474 if (downloadPath.equals(INVALID_PATH)) {
475 new AlertDialog.Builder(activity)
476 .setTitle(R.string.path_wrong)
477 .setIcon(android.R.drawable.ic_dialog_alert)
478 .setMessage(R.string.invalid_path)
479 .setPositiveButton(R.string.ok, null)
480 .show();
481 return false;
482 }
483
484 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
485 String status = getExternalStorageState(activity);
486 if (!status.equals(Environment.MEDIA_MOUNTED)) {
487 int title;
488 String msg;
489
490 // Check to see if the SDCard is busy, same as the music app
491 if (status.equals(Environment.MEDIA_SHARED)) {
492 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
493 title = R.string.download_sdcard_busy_dlg_title;
494 } else {
495 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
496 title = R.string.download_no_sdcard_dlg_title;
497 }
498
499 new AlertDialog.Builder(activity)
500 .setTitle(title)
501 .setIcon(android.R.drawable.ic_dialog_alert)
502 .setMessage(msg)
503 .setPositiveButton(R.string.ok, null)
504 .show();
505 return false;
506 }
507 } else {
508 String status = Environment.getExternalStorageState();
509 if (!status.equals(Environment.MEDIA_MOUNTED)) {
510 int mTitle = R.string.download_path_unavailable_dlg_title;
511 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
512 new AlertDialog.Builder(activity)
513 .setTitle(mTitle)
514 .setIcon(android.R.drawable.ic_dialog_alert)
515 .setMessage(mMsg)
516 .setPositiveButton(R.string.ok, null)
517 .show();
518 return false;
519 }
520 }
521 return true;
522 }
523
524 /**
525 * wheather support Phone Storage
526 *
527 * @return boolean true support Phone Storage ,false will be not
528 */
529 public static boolean isPhoneStorageSupported() {
530 return true;
531 }
532
533 /**
534 * show Dialog to warn filename is null
535 *
536 * @param activity
537 */
538 public static void showFilenameEmptyDialog(Activity activity) {
539 new AlertDialog.Builder(activity)
540 .setTitle(R.string.filename_empty_title)
541 .setIcon(android.R.drawable.ic_dialog_alert)
542 .setMessage(R.string.filename_empty_msg)
543 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
544 public void onClick(DialogInterface dialog, int which) {
545 }
546 })
547 .show();
548 }
549
550 /**
551 * get the filename except the suffix and dot
552 *
553 * @return String the filename except suffix and dot
554 */
555 public static String getFilenameBase(String filename) {
556 int dotindex = filename.lastIndexOf('.');
557 if (dotindex != -1) {
558 return filename.substring(0, dotindex);
559 } else {
560 return "";
561 }
562 }
563
564 /**
565 * get the filename's extension from filename
566 *
567 * @param filename the download filename, may be the user entered
568 * @return String the filename's extension
569 */
570 public static String getFilenameExtension(String filename) {
571 int dotindex = filename.lastIndexOf('.');
572 if (dotindex != -1) {
573 return filename.substring(dotindex + 1);
574 } else {
575 return "";
576 }
577 }
578
579 public static String getDefaultDownloadPath(Context context) {
580 String defaultDownloadPath;
581
582 String defaultStorage;
583 if (isPhoneStorageSupported()) {
584 defaultStorage = Environment.getExternalStorageDirectory().getPath();
585 } else {
586 defaultStorage = getExternalStorageDirectory(context);
587 }
588
kaiyize6a27d02013-08-22 15:08:19 +0800589 defaultDownloadPath = defaultStorage + context.getString(R.string.download_default_path);
luxiaol62677b02013-07-22 07:54:49 +0800590 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
591 return defaultDownloadPath;
592 }
593
594 /**
595 * translate the directory name into a name which is easy to know for user
596 *
597 * @param activity
598 * @param downloadPath
599 * @return String
600 */
601 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
602 if (downloadPath == null) {
603 return downloadPath;
604 }
605 final String phoneStorageDir;
606 final String sdCardDir = getExternalStorageDirectory(activity);
607 if (isPhoneStorageSupported()) {
608 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
609 } else {
610 phoneStorageDir = null;
611 }
612
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800613 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800614 String sdCardLabel = activity.getResources().getString(
615 R.string.download_path_sd_card_label);
616 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
617 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
618 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800619 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800620 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
621 }
622 return downloadPath;
623 }
624
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800625 private static boolean isRemovable(Object obj) {
626 return (Boolean) ReflectHelper.invokeMethod(obj,
627 "isRemovable", null, null);
628 }
629
630 private static boolean allowMassStorage(Object obj) {
631 return (Boolean) ReflectHelper.invokeMethod(obj,
632 "allowMassStorage", null, null);
633 }
634
635 private static String getPath(Object obj) {
636 return (String) ReflectHelper.invokeMethod(obj,
637 "getPath", null, null);
638 }
639
luxiaol62677b02013-07-22 07:54:49 +0800640 private static String getExternalStorageDirectory(Context context) {
641 String sd = null;
642 StorageManager mStorageManager = (StorageManager) context
643 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800644 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
645 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800646 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800647 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
648 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700649 break;
luxiaol62677b02013-07-22 07:54:49 +0800650 }
651 }
652 return sd;
653 }
654
655 private static String getExternalStorageState(Context context) {
656 StorageManager mStorageManager = (StorageManager) context
657 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800658 String path = getExternalStorageDirectory(context);
659 Object[] params = {path};
660 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700661 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800662 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800663 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700664}