下面列出了android.app.DownloadManager.Request#setAllowedNetworkTypes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void download(DownloadTask task) {
//TODO better path
DownloadManager downloadManager = (DownloadManager) UpodsApplication.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri episodUri = Uri.parse(task.track.getAudeoUrl());
String trackName = GlobalUtils.getCleanFileName(task.track.getTitle()) + ".mp3";
String mediaItemName = GlobalUtils.getCleanFileName(task.mediaItem.getName());
String finalPath = PODCASTS_DOWNLOAD_DIRECTORY + "/" + mediaItemName + "/" + trackName;
finalPath = Environment.getExternalStorageDirectory() + finalPath;
Request request = new Request(episodUri);
request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
request.setTitle(task.track.getTitle());
request.setDescription(task.track.getSubTitle());
request.setDestinationUri(Uri.fromFile(new File(finalPath)));
task.downloadId = downloadManager.enqueue(request);
task.filePath = finalPath;
allTasks.add(task);
Logger.printInfo(DM_LOG, "Starting download episod " + trackName + " to " + finalPath);
runProgressUpdater();
}
public void downloadIssue() {
if(!this.canDisplayPdf(getActivity())) {
Toast.makeText(getActivity(), getActivity().getString(R.string.pdf_reader_required), Toast.LENGTH_LONG).show();
return;
}
String file = issue.getId() + ".pdf";
File magPiFolder = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER);
magPiFolder.mkdirs();
File pdf = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER, file);
if(pdf.exists() && !isDownloading(issue.getPdfUrl())) {
Intent intentPdf = new Intent(Intent.ACTION_VIEW);
intentPdf.setDataAndType(Uri.fromFile(pdf), "application/pdf");
startActivity(intentPdf);
} else if (!isDownloading(issue.getPdfUrl())) {
menu.findItem(R.id.menu_view).setVisible(false);
menu.findItem(R.id.menu_cancel_download).setVisible(true);
Request request = new Request(Uri.parse(issue.getPdfUrl()));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle(getActivity().getString(R.string.app_name) + " n�" + issue.getId());
request.setDescription(getActivity().getString(R.string.download_text) + " n�" + issue.getId());
request.setDestinationInExternalPublicDir(Config.ISSUE_FOLDER, file);
dm.enqueue(request);
}
}
/**
* Download latest metadata from the server through DownloadManager for all relevant clients
*
* @param context The context for retrieving resources
* @param metadataUri The client to update
*/
private static void updateClientsWithMetadataUri(
final Context context, final String metadataUri) {
Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".json";
final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
DebugLogUtils.l("Request =", metadataRequest);
final Resources res = context.getResources();
metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
metadataRequest.setTitle(res.getString(R.string.download_description));
// Do not show the notification when downloading the metadata.
metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
metadataRequest.setVisibleInDownloadsUi(
res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
// We already have a recent download in progress. Don't register a new download.
return;
}
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(metadataRequest);
DebugLogUtils.l("Metadata download requested with id", downloadId);
// If there is still a download in progress, it's been there for a while and
// there is probably something wrong with download manager. It's best to just
// overwrite the id and request it again. If the old one happens to finish
// anyway, we don't know about its ID any more, so the downloadFinished
// method will ignore it.
writeMetadataDownloadId(context, metadataUri, downloadId);
}
Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
/**
* Download latest metadata from the server through DownloadManager for all relevant clients
*
* @param context The context for retrieving resources
* @param metadataUri The client to update
*/
private static void updateClientsWithMetadataUri(
final Context context, final String metadataUri) {
Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".json";
final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
DebugLogUtils.l("Request =", metadataRequest);
final Resources res = context.getResources();
metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
metadataRequest.setTitle(res.getString(R.string.download_description));
// Do not show the notification when downloading the metadata.
metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
metadataRequest.setVisibleInDownloadsUi(
res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
// We already have a recent download in progress. Don't register a new download.
return;
}
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(metadataRequest);
DebugLogUtils.l("Metadata download requested with id", downloadId);
// If there is still a download in progress, it's been there for a while and
// there is probably something wrong with download manager. It's best to just
// overwrite the id and request it again. If the old one happens to finish
// anyway, we don't know about its ID any more, so the downloadFinished
// method will ignore it.
writeMetadataDownloadId(context, metadataUri, downloadId);
}
Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
@Override
public synchronized long addDownload(File destFolder, String url, boolean wifiOnly, String title) {
long dmid = -1;
//Need to check first if the download manager service is enabled
if(!isDownloadManagerEnabled())
return dmid;
// skip if URL is not valid
if(url == null) {
// URL is null
return dmid;
}
url = url.trim();
if (url.length() == 0) {
// URL is empty
return dmid;
}
logger.debug("Starting download: " + url);
Uri target = Uri.fromFile(new File(destFolder, Sha1Util.SHA1(url)));
Request request = new Request(Uri.parse(url));
request.setDestinationUri(target);
request.setTitle(title);
if (wifiOnly) {
request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
} else {
request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
}
dmid = dm.enqueue(request);
return dmid;
}
/**
* Download latest metadata from the server through DownloadManager for all relevant clients
*
* @param context The context for retrieving resources
* @param metadataUri The client to update
*/
private static void updateClientsWithMetadataUri(
final Context context, final String metadataUri) {
Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".json";
final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
DebugLogUtils.l("Request =", metadataRequest);
final Resources res = context.getResources();
metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
metadataRequest.setTitle(res.getString(R.string.download_description));
// Do not show the notification when downloading the metadata.
metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
metadataRequest.setVisibleInDownloadsUi(
res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
// We already have a recent download in progress. Don't register a new download.
return;
}
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(metadataRequest);
DebugLogUtils.l("Metadata download requested with id", downloadId);
// If there is still a download in progress, it's been there for a while and
// there is probably something wrong with download manager. It's best to just
// overwrite the id and request it again. If the old one happens to finish
// anyway, we don't know about its ID any more, so the downloadFinished
// method will ignore it.
writeMetadataDownloadId(context, metadataUri, downloadId);
}
Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
@Override
public void execute(final Context context) {
if (null == mWordList) { // This should never happen
Log.e(TAG, "UpdateAction with a null parameter!");
return;
}
DebugLogUtils.l("Downloading word list");
final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
mWordList.mId, mWordList.mVersion);
final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
// The word list is still downloading. Cancel the download and revert the
// word list status to "available".
manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
} else if (MetadataDbHelper.STATUS_AVAILABLE != status
&& MetadataDbHelper.STATUS_RETRYING != status) {
// Should never happen
Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
+ " for an upgrade action. Fall back to download.");
}
// Download it.
DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);
// This is an upgraded word list: we should download it.
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".dict";
final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
final Request request = new Request(uri);
final Resources res = context.getResources();
request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
request.setTitle(mWordList.mDescription);
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(
res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));
final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
mWordList.mId, mWordList.mVersion);
Log.i(TAG, String.format("Starting the dictionary download with version:"
+ " %d and Url: %s", mWordList.mVersion, uri));
DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
@Override
public void execute(final Context context) {
if (null == mWordList) { // This should never happen
Log.e(TAG, "UpdateAction with a null parameter!");
return;
}
DebugLogUtils.l("Downloading word list");
final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
mWordList.mId, mWordList.mVersion);
final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
// The word list is still downloading. Cancel the download and revert the
// word list status to "available".
manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
} else if (MetadataDbHelper.STATUS_AVAILABLE != status
&& MetadataDbHelper.STATUS_RETRYING != status) {
// Should never happen
Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
+ " for an upgrade action. Fall back to download.");
}
// Download it.
DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);
// This is an upgraded word list: we should download it.
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".dict";
final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
final Request request = new Request(uri);
final Resources res = context.getResources();
request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
request.setTitle(mWordList.mDescription);
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(
res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));
final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
mWordList.mId, mWordList.mVersion);
Log.i(TAG, String.format("Starting the dictionary download with version:"
+ " %d and Url: %s", mWordList.mVersion, uri));
DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
@Override
public void execute(final Context context) {
if (null == mWordList) { // This should never happen
Log.e(TAG, "UpdateAction with a null parameter!");
return;
}
DebugLogUtils.l("Downloading word list");
final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
mWordList.mId, mWordList.mVersion);
final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
// The word list is still downloading. Cancel the download and revert the
// word list status to "available".
manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
} else if (MetadataDbHelper.STATUS_AVAILABLE != status
&& MetadataDbHelper.STATUS_RETRYING != status) {
// Should never happen
Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
+ " for an upgrade action. Fall back to download.");
}
// Download it.
DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);
// This is an upgraded word list: we should download it.
// Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
// DownloadManager also stupidly cuts the extension to replace with its own that it
// gets from the content-type. We need to circumvent this.
final String disambiguator = "#" + System.currentTimeMillis()
+ ApplicationUtils.getVersionName(context) + ".dict";
final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
final Request request = new Request(uri);
final Resources res = context.getResources();
request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
request.setTitle(mWordList.mDescription);
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(
res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));
final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
mWordList.mId, mWordList.mVersion);
Log.i(TAG, String.format("Starting the dictionary download with version:"
+ " %d and Url: %s", mWordList.mVersion, uri));
DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
@Override
public Void run(JobContext jc) {
try {
if (checkDownloadRunning())
return null;
if (checkApkExist()) {
Intent installApkIntent = new Intent();
installApkIntent.setAction(Intent.ACTION_VIEW);
installApkIntent.setDataAndType(
Uri.parse(Preferences.getDownloadPath(mContext)),
"application/vnd.android.package-archive");
installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
mContext.startActivity(installApkIntent);
} else {
String apkName = mContext.getPackageName()
+ System.currentTimeMillis() + Constants.APK_SUFFIX;
// 系统下载程序
final DownloadManager downloadManager = (DownloadManager) mContext
.getSystemService(mContext.DOWNLOAD_SERVICE);
Long recommendedMaxBytes = DownloadManager
.getRecommendedMaxBytesOverMobile(mContext);
// 可以在移动网络下下载
if (recommendedMaxBytes == null
|| recommendedMaxBytes.longValue() > MAX_ALLOWED_DOWNLOAD_BYTES_BY_MOBILE) {
allowMobileDownload = true;
}
Uri uri = Uri.parse(mUpgradeInfo.getUrl());
final Request request = new Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
int NETWORK_TYPE = DownloadManager.Request.NETWORK_WIFI;
if (allowMobileDownload) {
NETWORK_TYPE |= DownloadManager.Request.NETWORK_MOBILE;
}
request.setAllowedNetworkTypes(NETWORK_TYPE);
request.allowScanningByMediaScanner();
request.setShowRunningNotification(true);
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, apkName);
PackageManager packageManager = mContext.getPackageManager();
ApplicationInfo applicationInfo = packageManager
.getApplicationInfo(mContext.getPackageName(), 0);
Log.i("liweiping",
"appName = "
+ packageManager
.getApplicationLabel(applicationInfo));
request.setTitle(packageManager
.getApplicationLabel(applicationInfo));
request.setMimeType("application/vnd.android.package-archive");
// id 保存起来跟之后的广播接收器作对比
long id = downloadManager.enqueue(request);
long oldId = Preferences.getDownloadId(mContext);
if (oldId != -1) {
downloadManager.remove(oldId);
}
Preferences.removeAll(mContext);
Preferences.setDownloadId(mContext, id);
Preferences.setUpgradeInfo(mContext, mUpgradeInfo);
Preferences.setDownloadStatus(mContext,
Constants.DOWNLOAD_STATUS_RUNNING);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Void run(JobContext jc) {
try {
if (checkDownloadRunning())
return null;
if (checkApkExist()) {
Intent installApkIntent = new Intent();
installApkIntent.setAction(Intent.ACTION_VIEW);
installApkIntent.setDataAndType(
Uri.parse(Preferences.getDownloadPath(mContext)),
"application/vnd.android.package-archive");
installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
mContext.startActivity(installApkIntent);
} else {
String apkName = mContext.getPackageName()
+ System.currentTimeMillis() + Constants.APK_SUFFIX;
// 系统下载程序
final DownloadManager downloadManager = (DownloadManager) mContext
.getSystemService(mContext.DOWNLOAD_SERVICE);
Long recommendedMaxBytes = DownloadManager
.getRecommendedMaxBytesOverMobile(mContext);
// 可以在移动网络下下载
if (recommendedMaxBytes == null
|| recommendedMaxBytes.longValue() > MAX_ALLOWED_DOWNLOAD_BYTES_BY_MOBILE) {
allowMobileDownload = true;
}
Uri uri = Uri.parse(mUpgradeInfo.getUrl());
final Request request = new Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
int NETWORK_TYPE = DownloadManager.Request.NETWORK_WIFI;
if (allowMobileDownload) {
NETWORK_TYPE |= DownloadManager.Request.NETWORK_MOBILE;
}
request.setAllowedNetworkTypes(NETWORK_TYPE);
request.allowScanningByMediaScanner();
request.setShowRunningNotification(true);
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, apkName);
PackageManager packageManager = mContext.getPackageManager();
ApplicationInfo applicationInfo = packageManager
.getApplicationInfo(mContext.getPackageName(), 0);
Log.i("liweiping",
"appName = "
+ packageManager
.getApplicationLabel(applicationInfo));
request.setTitle(packageManager
.getApplicationLabel(applicationInfo));
request.setMimeType("application/vnd.android.package-archive");
// id 保存起来跟之后的广播接收器作对比
long id = downloadManager.enqueue(request);
long oldId = Preferences.getDownloadId(mContext);
if (oldId != -1) {
downloadManager.remove(oldId);
}
Preferences.removeAll(mContext);
Preferences.setDownloadId(mContext, id);
Preferences.setUpgradeInfo(mContext, mUpgradeInfo);
Preferences.setDownloadStatus(mContext,
Constants.DOWNLOAD_STATUS_RUNNING);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}