There are several ways to achieve this goal,
One simplest way I tried & succeed below is to use DownloadManager class (GingerBread and newer only):
1. check if download manager is available:
2. if step 1 checked OK, download from some URL:
/**
* @param context used to check the
device version and DownloadManager information
* @return true if the download manager
is available
*/
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
2. if step 1 checked OK, download from some URL:
String url = "some url path";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("to /sdcard/download");
request.setTitle("some string");
// in order for this if to run, you must use the android
3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.
VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "some string");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
沒有留言:
張貼留言