blob: 1de6ac6faf9881287142aaf4824750958a199e1b [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
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080044import java.io.File;
Michael Kolb8233fac2010-10-26 16:08:53 -070045/**
46 * Handle download requests
47 */
48public class DownloadHandler {
49
50 private static final boolean LOGD_ENABLED =
Bijan Amirzada41242f22014-03-21 12:12:18 -070051 com.android.browser.Browser.LOGD_ENABLED;
Michael Kolb8233fac2010-10-26 16:08:53 -070052
53 private static final String LOGTAG = "DLHandler";
luxiaol62677b02013-07-22 07:54:49 +080054 private static String mInternalStorage;
55 private static String mExternalStorage;
56 private final static String INVALID_PATH = "/storage";
Michael Kolb8233fac2010-10-26 16:08:53 -070057
luxiaol62677b02013-07-22 07:54:49 +080058 public static void startingDownload(Activity activity,
59 String url, String userAgent, String contentDisposition,
60 String mimetype, String referer, boolean privateBrowsing, long contentLength,
61 String filename, String downloadPath) {
62 // java.net.URI is a lot stricter than KURL so we have to encode some
63 // extra characters. Fix for b 2538060 and b 1634719
64 WebAddress webAddress;
65 try {
66 webAddress = new WebAddress(url);
67 webAddress.setPath(encodePath(webAddress.getPath()));
68 } catch (Exception e) {
69 // This only happens for very bad urls, we want to chatch the
70 // exception here
71 Log.e(LOGTAG, "Exception trying to parse url:" + url);
72 return;
73 }
74
75 String addressString = webAddress.toString();
76 Uri uri = Uri.parse(addressString);
77 final DownloadManager.Request request;
78 try {
79 request = new DownloadManager.Request(uri);
80 } catch (IllegalArgumentException e) {
81 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
82 return;
83 }
84 request.setMimeType(mimetype);
85 // set downloaded file destination to /sdcard/Download.
86 // or, should it be set to one of several Environment.DIRECTORY* dirs
87 // depending on mimetype?
88 try {
89 setDestinationDir(downloadPath, filename, request);
90 } catch (Exception e) {
91 showNoEnoughMemoryDialog(activity);
92 return;
93 }
94 // let this downloaded file be scanned by MediaScanner - so that it can
95 // show up in Gallery app, for example.
96 request.allowScanningByMediaScanner();
97 request.setDescription(webAddress.getHost());
98 // XXX: Have to use the old url since the cookies were stored using the
99 // old percent-encoded url.
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800100
luxiaol62677b02013-07-22 07:54:49 +0800101 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
102 request.addRequestHeader("cookie", cookies);
103 request.addRequestHeader("User-Agent", userAgent);
104 request.addRequestHeader("Referer", referer);
105 request.setNotificationVisibility(
106 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
107 final DownloadManager manager = (DownloadManager) activity
108 .getSystemService(Context.DOWNLOAD_SERVICE);
109 new Thread("Browser download") {
110 public void run() {
111 manager.enqueue(request);
112 }
113 }.start();
114 showStartDownloadToast(activity);
115 }
116
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800117 private static boolean isAudioFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700118 Object[] params = {Integer.valueOf(fileType)};
119 Class[] type = new Class[] {int.class};
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800120 Boolean result = (Boolean) ReflectHelper.invokeStaticMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700121 "isAudioFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800122 return result;
123 }
124
125 private static boolean isVideoFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700126 Object[] params = {Integer.valueOf(fileType)};
127 Class[] type = new Class[] {int.class};
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800128 Boolean result = (Boolean) ReflectHelper.invokeStaticMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700129 "isVideoFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800130 return result;
131 }
132
kaiyize6a27d02013-08-22 15:08:19 +0800133 /**
134 * Notify the host application a download should be done, or that
135 * the data should be streamed if a streaming viewer is available.
136 * @param activity Activity requesting the download.
137 * @param url The full url to the content that should be downloaded
138 * @param userAgent User agent of the downloading application.
139 * @param contentDisposition Content-disposition http header, if present.
140 * @param mimetype The mimetype of the content reported by the server
141 * @param referer The referer associated with the downloaded url
142 * @param privateBrowsing If the request is coming from a private browsing tab.
143 */
qqzhoua95a2e22013-04-18 17:28:31 +0800144 public static boolean onDownloadStart(final Activity activity, final String url,
145 final String userAgent, final String contentDisposition, final String mimetype,
luxiaol62677b02013-07-22 07:54:49 +0800146 final String referer, final boolean privateBrowsing, final long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 // if we're dealing wih A/V content that's not explicitly marked
148 // for download, check if it's streamable.
149 if (contentDisposition == null
150 || !contentDisposition.regionMatches(
151 true, 0, "attachment", 0, 10)) {
qqzhoua95a2e22013-04-18 17:28:31 +0800152 // Add for Carrier Feature - When open an audio/video link, prompt a dialog
153 // to let the user choose play or download operation.
154 Uri uri = Uri.parse(url);
155 String scheme = uri.getScheme();
156 Log.v(LOGTAG, "scheme:" + scheme + ", mimetype:" + mimetype);
157 // Some mimetype for audio/video files is not started with "audio" or "video",
158 // such as ogg audio file with mimetype "application/ogg". So we also check
159 // file type by MediaFile.isAudioFileType() and MediaFile.isVideoFileType().
160 // For those file types other than audio or video, download it immediately.
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700161 Object[] params = {mimetype};
162 Class[] type = new Class[] {String.class};
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800163 Integer result = (Integer) ReflectHelper.invokeStaticMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700164 "getFileTypeForMimeType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800165 int fileType = result.intValue();
qqzhoua95a2e22013-04-18 17:28:31 +0800166 if ("http".equalsIgnoreCase(scheme) &&
167 (mimetype.startsWith("audio/") ||
168 mimetype.startsWith("video/") ||
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800169 isAudioFileType(fileType) ||
170 isVideoFileType(fileType))) {
qqzhoua95a2e22013-04-18 17:28:31 +0800171 new AlertDialog.Builder(activity)
172 .setTitle(R.string.application_name)
173 .setIcon(R.drawable.default_video_poster)
174 .setMessage(R.string.http_video_msg)
175 .setPositiveButton(R.string.video_save, new DialogInterface.OnClickListener() {
176 public void onClick(DialogInterface dialog, int which) {
177 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800178 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800179 }
180 })
181 .setNegativeButton(R.string.video_play, new DialogInterface.OnClickListener() {
182 public void onClick(DialogInterface dialog, int which) {
183 Intent intent = new Intent(Intent.ACTION_VIEW);
184 intent.setDataAndType(Uri.parse(url), mimetype);
185 try {
186 String title = URLUtil.guessFileName(url, contentDisposition, mimetype);
187 intent.putExtra(Intent.EXTRA_TITLE, title);
188 activity.startActivity(intent);
189 } catch (ActivityNotFoundException ex) {
190 Log.w(LOGTAG, "When http stream play, activity not found for "
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700191 + mimetype + " over " + Uri.parse(url).getScheme(), ex);
qqzhoua95a2e22013-04-18 17:28:31 +0800192 }
193 }
194 }).show();
195
196 return true;
197 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700198 // query the package manager to see if there's a registered handler
199 // that matches.
200 Intent intent = new Intent(Intent.ACTION_VIEW);
201 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500202 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700203 PackageManager.MATCH_DEFAULT_ONLY);
204 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500205 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700206 // If we resolved to ourselves, we don't want to attempt to
207 // load the url only to try and download it again.
208 if (!myName.getPackageName().equals(
209 info.activityInfo.packageName)
210 || !myName.getClassName().equals(
211 info.activityInfo.name)) {
212 // someone (other than us) knows how to handle this mime
213 // type with this scheme, don't download.
214 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500215 activity.startActivity(intent);
qqzhoua95a2e22013-04-18 17:28:31 +0800216 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700217 } catch (ActivityNotFoundException ex) {
218 if (LOGD_ENABLED) {
219 Log.d(LOGTAG, "activity not found for " + mimetype
220 + " over " + Uri.parse(url).getScheme(),
221 ex);
222 }
223 // Best behavior is to fall back to a download in this
224 // case
225 }
226 }
227 }
228 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500229 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800230 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800231 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700232 }
233
234 // This is to work around the fact that java.net.URI throws Exceptions
235 // instead of just encoding URL's properly
236 // Helper method for onDownloadStartNoStream
237 private static String encodePath(String path) {
238 char[] chars = path.toCharArray();
239
240 boolean needed = false;
241 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700242 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700243 needed = true;
244 break;
245 }
246 }
247 if (needed == false) {
248 return path;
249 }
250
251 StringBuilder sb = new StringBuilder("");
252 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700253 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700254 sb.append('%');
255 sb.append(Integer.toHexString(c));
256 } else {
257 sb.append(c);
258 }
259 }
260
261 return sb.toString();
262 }
263
264 /**
265 * Notify the host application a download should be done, even if there
266 * is a streaming viewer available for thise type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500267 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500269 * @param userAgent User agent of the downloading application.
270 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700272 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000273 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700274 */
luxiaol62677b02013-07-22 07:54:49 +0800275 /* package */static void onDownloadStartNoStream(Activity activity,
Leon Scroggins63c02662010-11-18 15:16:27 -0500276 String url, String userAgent, String contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800277 String mimetype, String referer, boolean privateBrowsing, long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700278
luxiaol62677b02013-07-22 07:54:49 +0800279 initStorageDefaultPath(activity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700280 String filename = URLUtil.guessFileName(url,
281 contentDisposition, mimetype);
282
283 // Check to see if we have an SDCard
284 String status = Environment.getExternalStorageState();
285 if (!status.equals(Environment.MEDIA_MOUNTED)) {
286 int title;
287 String msg;
288
289 // Check to see if the SDCard is busy, same as the music app
290 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500291 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700292 title = R.string.download_sdcard_busy_dlg_title;
293 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500294 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700295 title = R.string.download_no_sdcard_dlg_title;
296 }
297
Leon Scroggins63c02662010-11-18 15:16:27 -0500298 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700299 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200300 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700301 .setMessage(msg)
302 .setPositiveButton(R.string.ok, null)
303 .show();
304 return;
305 }
306
Michael Kolb8233fac2010-10-26 16:08:53 -0700307 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700308 // We must have long pressed on a link or image to download it. We
309 // are not sure of the mimetype in this case, so do a head request
luxiaol62677b02013-07-22 07:54:49 +0800310 new FetchUrlMimeType(activity, url, userAgent, referer,
311 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700312 } else {
luxiaol62677b02013-07-22 07:54:49 +0800313 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
314 privateBrowsing, contentLength, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700315 }
luxiaol62677b02013-07-22 07:54:49 +0800316
317 }
318
319 public static void initStorageDefaultPath(Context context) {
320 mExternalStorage = getExternalStorageDirectory(context);
321 if (isPhoneStorageSupported()) {
322 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
323 } else {
324 mInternalStorage = null;
325 }
326 }
327
328 public static void startDownloadSettings(Activity activity,
329 String url, String userAgent, String contentDisposition,
330 String mimetype, String referer, boolean privateBrowsing, long contentLength,
331 String filename) {
332 Bundle fileInfo = new Bundle();
333 fileInfo.putString("url", url);
334 fileInfo.putString("userAgent", userAgent);
335 fileInfo.putString("contentDisposition", contentDisposition);
336 fileInfo.putString("mimetype", mimetype);
337 fileInfo.putString("referer", referer);
338 fileInfo.putLong("contentLength", contentLength);
339 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
340 fileInfo.putString("filename", filename);
341 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
342 intent.putExtras(fileInfo);
343 activity.startActivity(intent);
344 }
345
346 public static void setAppointedFolder(String downloadPath) {
347 File file = new File(downloadPath);
348 if (file.exists()) {
349 if (!file.isDirectory()) {
350 throw new IllegalStateException(file.getAbsolutePath() +
351 " already exists and is not a directory");
352 }
353 } else {
354 if (!file.mkdir()) {
355 throw new IllegalStateException("Unable to create directory: " +
356 file.getAbsolutePath());
357 }
358 }
359 }
360
361 private static void setDestinationDir(String downloadPath, String filename, Request request) {
362 File file = new File(downloadPath);
363 if (file.exists()) {
364 if (!file.isDirectory()) {
365 throw new IllegalStateException(file.getAbsolutePath() +
366 " already exists and is not a directory");
367 }
368 } else {
369 if (!file.mkdir()) {
370 throw new IllegalStateException("Unable to create directory: " +
371 file.getAbsolutePath());
372 }
373 }
374 setDestinationFromBase(file, filename, request);
375 }
376
377 private static void setDestinationFromBase(File file, String filename, Request request) {
378 if (filename == null) {
379 throw new NullPointerException("filename cannot be null");
380 }
381 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
382 }
383
384 public static void fileExistQueryDialog(Activity activity) {
385 new AlertDialog.Builder(activity)
386 .setTitle(R.string.download_file_exist)
387 .setIcon(android.R.drawable.ic_dialog_info)
388 .setMessage(R.string.download_file_exist_msg)
389 // if yes, delete existed file and start new download thread
390 .setPositiveButton(R.string.ok, null)
391 // if no, do nothing at all
392 .show();
393 }
394
395 public static long getAvailableMemory(String root) {
396 StatFs stat = new StatFs(root);
397 final long LEFT10MByte = 2560;
398 long blockSize = stat.getBlockSize();
399 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
400 return availableBlocks * blockSize;
401 }
402
403 public static void showNoEnoughMemoryDialog(Activity mContext) {
404 new AlertDialog.Builder(mContext)
405 .setTitle(R.string.download_no_enough_memory)
406 .setIconAttribute(android.R.attr.alertDialogIcon)
407 .setMessage(R.string.download_no_enough_memory)
408 .setPositiveButton(R.string.ok, null)
409 .show();
410 }
411
kaiyize6a27d02013-08-22 15:08:19 +0800412 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800413 long mAvailableBytes = getAvailableMemory(root);
414 if (mAvailableBytes > 0) {
415 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800416 return true;
417 }
418 } else {
luxiaol62677b02013-07-22 07:54:49 +0800419 return true;
420 }
421 return false;
422 }
423
424 public static void showStartDownloadToast(Activity activity) {
425 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
426 activity.startActivity(intent);
Leon Scroggins63c02662010-11-18 15:16:27 -0500427 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700428 .show();
429 }
430
luxiaol62677b02013-07-22 07:54:49 +0800431 /**
432 * wheather the storage status OK for download file
433 *
434 * @param activity
435 * @param filename the download file's name
436 * @param downloadPath the download file's path will be in
437 * @return boolean true is ok,and false is not
438 */
439 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
440 if (downloadPath.equals(INVALID_PATH)) {
441 new AlertDialog.Builder(activity)
442 .setTitle(R.string.path_wrong)
443 .setIcon(android.R.drawable.ic_dialog_alert)
444 .setMessage(R.string.invalid_path)
445 .setPositiveButton(R.string.ok, null)
446 .show();
447 return false;
448 }
449
450 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
451 String status = getExternalStorageState(activity);
452 if (!status.equals(Environment.MEDIA_MOUNTED)) {
453 int title;
454 String msg;
455
456 // Check to see if the SDCard is busy, same as the music app
457 if (status.equals(Environment.MEDIA_SHARED)) {
458 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
459 title = R.string.download_sdcard_busy_dlg_title;
460 } else {
461 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
462 title = R.string.download_no_sdcard_dlg_title;
463 }
464
465 new AlertDialog.Builder(activity)
466 .setTitle(title)
467 .setIcon(android.R.drawable.ic_dialog_alert)
468 .setMessage(msg)
469 .setPositiveButton(R.string.ok, null)
470 .show();
471 return false;
472 }
473 } else {
474 String status = Environment.getExternalStorageState();
475 if (!status.equals(Environment.MEDIA_MOUNTED)) {
476 int mTitle = R.string.download_path_unavailable_dlg_title;
477 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
478 new AlertDialog.Builder(activity)
479 .setTitle(mTitle)
480 .setIcon(android.R.drawable.ic_dialog_alert)
481 .setMessage(mMsg)
482 .setPositiveButton(R.string.ok, null)
483 .show();
484 return false;
485 }
486 }
487 return true;
488 }
489
490 /**
491 * wheather support Phone Storage
492 *
493 * @return boolean true support Phone Storage ,false will be not
494 */
495 public static boolean isPhoneStorageSupported() {
496 return true;
497 }
498
499 /**
500 * show Dialog to warn filename is null
501 *
502 * @param activity
503 */
504 public static void showFilenameEmptyDialog(Activity activity) {
505 new AlertDialog.Builder(activity)
506 .setTitle(R.string.filename_empty_title)
507 .setIcon(android.R.drawable.ic_dialog_alert)
508 .setMessage(R.string.filename_empty_msg)
509 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
510 public void onClick(DialogInterface dialog, int which) {
511 }
512 })
513 .show();
514 }
515
516 /**
517 * get the filename except the suffix and dot
518 *
519 * @return String the filename except suffix and dot
520 */
521 public static String getFilenameBase(String filename) {
522 int dotindex = filename.lastIndexOf('.');
523 if (dotindex != -1) {
524 return filename.substring(0, dotindex);
525 } else {
526 return "";
527 }
528 }
529
530 /**
531 * get the filename's extension from filename
532 *
533 * @param filename the download filename, may be the user entered
534 * @return String the filename's extension
535 */
536 public static String getFilenameExtension(String filename) {
537 int dotindex = filename.lastIndexOf('.');
538 if (dotindex != -1) {
539 return filename.substring(dotindex + 1);
540 } else {
541 return "";
542 }
543 }
544
545 public static String getDefaultDownloadPath(Context context) {
546 String defaultDownloadPath;
547
548 String defaultStorage;
549 if (isPhoneStorageSupported()) {
550 defaultStorage = Environment.getExternalStorageDirectory().getPath();
551 } else {
552 defaultStorage = getExternalStorageDirectory(context);
553 }
554
kaiyize6a27d02013-08-22 15:08:19 +0800555 defaultDownloadPath = defaultStorage + context.getString(R.string.download_default_path);
luxiaol62677b02013-07-22 07:54:49 +0800556 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
557 return defaultDownloadPath;
558 }
559
560 /**
561 * translate the directory name into a name which is easy to know for user
562 *
563 * @param activity
564 * @param downloadPath
565 * @return String
566 */
567 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
568 if (downloadPath == null) {
569 return downloadPath;
570 }
571 final String phoneStorageDir;
572 final String sdCardDir = getExternalStorageDirectory(activity);
573 if (isPhoneStorageSupported()) {
574 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
575 } else {
576 phoneStorageDir = null;
577 }
578
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800579 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800580 String sdCardLabel = activity.getResources().getString(
581 R.string.download_path_sd_card_label);
582 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
583 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
584 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800585 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800586 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
587 }
588 return downloadPath;
589 }
590
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800591 private static boolean isRemovable(Object obj) {
592 return (Boolean) ReflectHelper.invokeMethod(obj,
593 "isRemovable", null, null);
594 }
595
596 private static boolean allowMassStorage(Object obj) {
597 return (Boolean) ReflectHelper.invokeMethod(obj,
598 "allowMassStorage", null, null);
599 }
600
601 private static String getPath(Object obj) {
602 return (String) ReflectHelper.invokeMethod(obj,
603 "getPath", null, null);
604 }
605
luxiaol62677b02013-07-22 07:54:49 +0800606 private static String getExternalStorageDirectory(Context context) {
607 String sd = null;
608 StorageManager mStorageManager = (StorageManager) context
609 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800610 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
611 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800612 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800613 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
614 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700615 break;
luxiaol62677b02013-07-22 07:54:49 +0800616 }
617 }
618 return sd;
619 }
620
621 private static String getExternalStorageState(Context context) {
622 StorageManager mStorageManager = (StorageManager) context
623 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800624 String path = getExternalStorageDirectory(context);
625 Object[] params = {path};
626 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700627 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800628 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800629 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700630}