下面列出了怎么用android.app.DownloadManager.Request的API类实例代码及写法,或者点击链接到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();
}
private DownloadListener getDownloadListener() {
return new DownloadListener() {
public void onDownloadStart(
String url,
String userAgent,
String contentDisposition,
String mimetype,
long contentLength
) {
Uri uri = Uri.parse(url);
Request request = new Request(uri);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("File download from Mattermost");
String cookie = CookieManager.getInstance().getCookie(url);
if (cookie != null) {
request.addRequestHeader("cookie", cookie);
}
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
};
}
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 void onLrc(int position, String url) {
if(url == null) return;
String musicName = mResultData.get(position).getMusicName();
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(Constants.MUSIC_URL + url));
request.setVisibleInDownloadsUi(false);
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
// request.setShowRunningNotification(false);
request.setDestinationUri(Uri.fromFile(new File(MusicUtils
.getLrcDir() + musicName + ".lrc")));
mDownloadManager.enqueue(request);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void downloadApk(String requestUrl, String dir, String filename)
{
Uri resource = Uri.parse(requestUrl);
DownloadManager.Request request = new DownloadManager.Request(resource);
request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
//设置文件类型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(requestUrl));
request.setMimeType(mimeString);
//在通知栏中显示
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
{
request.setShowRunningNotification(true);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// 显示下载界面
request.setVisibleInDownloadsUi(true);
//sdcard的目录下的download文件夹 /**AppConfig.DIR_APK*/
request.setDestinationInExternalPublicDir("/download/", filename + ".apk");
request.setTitle(filename + "");
long id = mDownloadManager.enqueue(request);
mTask.put(id, filename + "");
}
@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;
}
public static void downloadPlugin(PluginDownloadHolder dataSource) {
Request request = new DownloadManager.Request(
dataSource.getDownloadLink());
request.setDestinationInExternalFilesDir(
GeoARApplication.applicationContext, null,
dataSource.getIdentifier() + ".apk");
request.setTitle("GeoAR Data Souce Download");
request.setMimeType("application/vnd.52north.datasources");
request.setDescription(dataSource.getName());
currentDownloads.add(mDownloadManager.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);
}
@Override
public void onClick(final View v) {
if (mDownloadUrl == null) {
return;
}
final DownloadManager downloadManager = (DownloadManager)v.getContext().getSystemService(DOWNLOAD_SERVICE);
final Request request = new Request(mDownloadUrl);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://www.vogella.de/img/lars/LarsVogelArticle7.png"));
enqueue = dm.enqueue(request);
}
@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);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static DownloadInfo add(Builder b) {
Context context = b.mContext;
removeAllForUrl(context, b.mUrl);
if (!b.mDialog) {
synchronized (mCallbacks) {
mCallbacks.put(b.mUrl, b.mCallback);
}
}
String savePath = "Download/EdXposedManager";
if (b.mModule) {
savePath += "/modules";
}
Request request = new Request(Uri.parse(b.mUrl));
request.setTitle(b.mTitle);
request.setMimeType(b.mMimeType.toString());
if (b.mSave) {
try {
request.setDestinationInExternalPublicDir(savePath, b.mTitle + b.mMimeType.getExtension());
} catch (IllegalStateException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else if (b.mDestination != null) {
b.mDestination.getParentFile().mkdirs();
removeAllForLocalFile(context, b.mDestination);
request.setDestinationUri(Uri.fromFile(b.mDestination));
}
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long id = dm.enqueue(request);
if (b.mDialog) {
showDownloadDialog(b, id);
}
return getById(context, id);
}
@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);
}
/**
* download map
*
* @param view View
* @param position item position
*/
private void onClickMapNow(int position)
{
MyMap myMap = myDownloadAdapter.getItem(position);
if (myMap.getStatus() == MyMap.DlStatus.Downloading || myMap.getStatus() == MyMap.DlStatus.Unzipping)
{
logUser("Already downloading!");
return;
}
else if (myMap.isUpdateAvailable())
{
MyMap myMapNew = null;
if (!myMap.getMapNameNew().isEmpty())
{
int removePos = -1;
for (int i= 0; i<myDownloadAdapter.getItemCount(); i++)
{
if (myDownloadAdapter.getItem(i).getMapName().equals(myMap.getMapName()))
{
removePos = i;
}
if (myDownloadAdapter.getItem(i).getMapName().equals(myMap.getMapNameNew()))
{
position = i;
myMapNew = myDownloadAdapter.getItem(i);
}
}
if (removePos < 0 || myMapNew == null)
{
logUser("OldMap or NewMap missing on json-list!");
return;
}
mapsRV.scrollToPosition(position);
myDownloadAdapter.remove(removePos);
if (position > removePos) { position--; }
}
MainActivity.clearLocalMap(myMap);
if (myMapNew != null)
{
myMap = myMapNew;
if (myMap.getStatus() != DlStatus.On_server)
{
logUser("New map is: " + myMap.getMapName());
return;
}
}
}
else if (myMap.getStatus() == MyMap.DlStatus.Complete)
{
logUser("Already downloaded!");
return;
}
myMap.setStatus(MyMap.DlStatus.Downloading);
myDownloadAdapter.refreshMapView(myMap);
String vers = "?v=unknown";
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try
{
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
vers = "?v=" + packageInfo.versionName;
}
catch (Exception e) {} // No problem, not important.
Request request = new Request(Uri.parse(myMap.getUrl() + vers));
File destFile = MyMap.getMapFile(myMap, MyMap.MapFileType.DlMapFile);
request.setDestinationUri(Uri.fromFile(destFile));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setMimeType("application/pocketmaps");
long enqueueId = dm.enqueue(request);
File idFile = MyMap.getMapFile(myMap, MyMap.MapFileType.DlIdFile);
IO.writeToFile("" + enqueueId, idFile, false);
BroadcastReceiver br = createBroadcastReceiver(this, createStatusUpdater(), myMap, enqueueId);
registerReceiver(br, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
receiverList.add(br);
}
@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;
}
/**
* Registers a download request and flags it as downloading in the metadata table.
*
* This is a helper method that exists to avoid race conditions where DownloadManager might
* finish downloading the file before the data is committed to the database.
* It registers the request with the DownloadManager service and also updates the metadata
* database directly within a synchronized section.
* This method has no intelligence about the data it commits to the database aside from the
* download request id, which is not known before submitting the request to the download
* manager. Hence, it only updates the relevant line.
*
* @param manager a wrapped download manager service to register the request with.
* @param request the request to register.
* @param db the metadata database.
* @param id the id of the word list.
* @param version the version of the word list.
* @return the download id returned by the download manager.
*/
public static long registerDownloadRequest(final DownloadManagerWrapper manager,
final Request request, final SQLiteDatabase db, final String id, final int version) {
Log.i(TAG, "registerDownloadRequest() : Id = " + id + " : Version = " + version);
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(request);
Log.i(TAG, "registerDownloadRequest() : DownloadId = " + downloadId);
MetadataDbHelper.markEntryAsDownloading(db, id, version, downloadId);
}
return downloadId;
}
/**
* Registers a download request and flags it as downloading in the metadata table.
*
* This is a helper method that exists to avoid race conditions where DownloadManager might
* finish downloading the file before the data is committed to the database.
* It registers the request with the DownloadManager service and also updates the metadata
* database directly within a synchronized section.
* This method has no intelligence about the data it commits to the database aside from the
* download request id, which is not known before submitting the request to the download
* manager. Hence, it only updates the relevant line.
*
* @param manager a wrapped download manager service to register the request with.
* @param request the request to register.
* @param db the metadata database.
* @param id the id of the word list.
* @param version the version of the word list.
* @return the download id returned by the download manager.
*/
public static long registerDownloadRequest(final DownloadManagerWrapper manager,
final Request request, final SQLiteDatabase db, final String id, final int version) {
Log.i(TAG, "registerDownloadRequest() : Id = " + id + " : Version = " + version);
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(request);
Log.i(TAG, "registerDownloadRequest() : DownloadId = " + downloadId);
MetadataDbHelper.markEntryAsDownloading(db, id, version, downloadId);
}
return downloadId;
}
/**
* Registers a download request and flags it as downloading in the metadata table.
*
* This is a helper method that exists to avoid race conditions where DownloadManager might
* finish downloading the file before the data is committed to the database.
* It registers the request with the DownloadManager service and also updates the metadata
* database directly within a synchronized section.
* This method has no intelligence about the data it commits to the database aside from the
* download request id, which is not known before submitting the request to the download
* manager. Hence, it only updates the relevant line.
*
* @param manager a wrapped download manager service to register the request with.
* @param request the request to register.
* @param db the metadata database.
* @param id the id of the word list.
* @param version the version of the word list.
* @return the download id returned by the download manager.
*/
public static long registerDownloadRequest(final DownloadManagerWrapper manager,
final Request request, final SQLiteDatabase db, final String id, final int version) {
Log.i(TAG, "registerDownloadRequest() : Id = " + id + " : Version = " + version);
final long downloadId;
synchronized (sSharedIdProtector) {
downloadId = manager.enqueue(request);
Log.i(TAG, "registerDownloadRequest() : DownloadId = " + downloadId);
MetadataDbHelper.markEntryAsDownloading(db, id, version, downloadId);
}
return downloadId;
}