下面列出了怎么用android.app.DownloadManager的API类实例代码及写法,或者点击链接到github查看源代码。
private @Nullable Uri getLocalUriForDownloadId(Context context, long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
try {
if (cursor != null && cursor.moveToFirst()) {
String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
if (localUri != null) {
File localFile = new File(Uri.parse(localUri).getPath());
return FileProviderUtil.getUriFor(context, localFile);
}
}
} finally {
if (cursor != null) cursor.close();
}
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
//just open the manage activity
intent.setClass(context, ManageDownloadsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
}
else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
// This is the only extra provided.
long id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
Log.d(LOG_TAG, "Download Complete: " + id);
Intent service = new Intent(context, KADataService.class);
service.setAction(ACTION_UPDATE_DOWNLOAD_STATUS);
service.putExtra(EXTRA_ID, id);
context.startService(service);
}
}
public DownloadInfo(long download_id, Context ctx)
{
long id = download_id;
DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = dm.query(new DownloadManager.Query().setFilterById(id));
if (!c.moveToFirst())
{
c.close();
return;
}
_last_modified = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
_local_uri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
_status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
_reason = c.getString(c.getColumnIndex(DownloadManager.COLUMN_REASON));
c.close();
_valid = true;
}
public int getProgress(Layer layer) {
int progress = 0;
Long downloadId = layer.getDownloadId();
if (downloadId != null) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
try (Cursor cursor = downloadManager.query(query)) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
if(columnIndex != -1) {
progress = cursor.getInt(columnIndex);
}
}
}
}
return progress;
}
@Override
public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder)
throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
Query query = new Query();
DownloadManagerUtils.setOnlyIncludeVisibleInDownloadsUi(query);
//query.setOnlyIncludeVisibleInDownloadsUi(true);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
//query.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_FAILED);
cursor = mDm.query(query);//.setOnlyIncludeVisibleInDownloadsUi(true)
//.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
/**
* 查询下载完成文件的状态
*/
private void checkDownloadStatus(Context context, long downloadId) {
mDownloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = mDownloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
LogUtil.d(LogUtil.TAG_COMMON, "下载完成!");
installApk(context,mDownloadManager.getUriForDownloadedFile(downloadId));
break;
case DownloadManager.STATUS_FAILED://下载失败
LogUtil.d(LogUtil.TAG_COMMON, "下载失败.....");
break;
case DownloadManager.STATUS_RUNNING://正在下载
LogUtil.d(LogUtil.TAG_COMMON, "正在下载.....");
break;
default:
break;
}
}
}
private void removeOldDownloads(Context context) {
try {
Log.i(TAG, "Removing the old downloads in progress of the previous keyboard version.");
final DownloadManagerWrapper downloadManagerWrapper = new DownloadManagerWrapper(
context);
final DownloadManager.Query q = new DownloadManager.Query();
// Query all the download statuses except the succeeded ones.
q.setFilterByStatus(DownloadManager.STATUS_FAILED
| DownloadManager.STATUS_PAUSED
| DownloadManager.STATUS_PENDING
| DownloadManager.STATUS_RUNNING);
final Cursor c = downloadManagerWrapper.query(q);
if (c != null) {
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
final long downloadId = c
.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
downloadManagerWrapper.remove(downloadId);
Log.i(TAG, "Removed the download with Id: " + downloadId);
}
c.close();
}
} catch (Exception e) {
Log.e(TAG, "Exception while removing old downloads.");
}
}
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);
}
}
/**
* @param versionNumber version number
* @return true if download was started;
*/
public boolean downloadApk(final int versionNumber) {
if (manager == null)
return false;
downloadingToast.show();
deleteCurrentUpdateFile();
final Uri uri =
Uri.parse(baldUpdateObject.apkUrl);
final DownloadManager.Request request =
new DownloadManager.Request(uri)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, FILENAME)
.setAllowedOverRoaming(true)
.setAllowedOverMetered(true)
.setDescription(getText(R.string.downloading_updates));
downloadId = manager.enqueue(request);
BPrefs.get(this).edit().putLong(BPrefs.LAST_DOWNLOAD_MANAGER_REQUEST_ID, downloadId).apply();
BPrefs.get(this).edit().putInt(BPrefs.LAST_DOWNLOAD_MANAGER_REQUEST_VERSION_NUMBER, versionNumber).apply();
apply();
return true;
}
/**
* Called to open a given download item that is downloaded by the android DownloadManager.
* @param context Context of the receiver.
* @param intent Intent from the android DownloadManager.
*/
private void openDownload(final Context context, Intent intent) {
long ids[] =
intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
if (ids == null || ids.length == 0) {
DownloadManagerService.openDownloadsPage(context);
return;
}
long id = ids[0];
DownloadManager manager =
(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = manager.getUriForDownloadedFile(id);
if (uri == null) {
// Open the downloads page
DownloadManagerService.openDownloadsPage(context);
} else {
Intent launchIntent = new Intent(Intent.ACTION_VIEW);
launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(id));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(launchIntent);
} catch (ActivityNotFoundException e) {
DownloadManagerService.openDownloadsPage(context);
}
}
}
@Override
public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder)
throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
Query query = new Query();
DownloadManagerUtils.setOnlyIncludeVisibleInDownloadsUi(query);
//query.setOnlyIncludeVisibleInDownloadsUi(true);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
//query.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_FAILED);
cursor = mDm.query(query);//.setOnlyIncludeVisibleInDownloadsUi(true)
//.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public void onReceive(Context context, Intent intent) {
/**
* get the id of download which have download success, if the id is
* my id and it's status is successful, then install it
**/
long completeDownloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (completeDownloadId == downloadId) {
initData();
updateView();
// if download successful, install apk
if (downloadManagerPro.getStatusById(downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
String apkFilePath = new StringBuilder(Environment
.getExternalStorageDirectory().getAbsolutePath())
.append(File.separator)
.append(DOWNLOAD_FOLDER_NAME)
.append(File.separator).append(DOWNLOAD_FILE_NAME)
.toString();
install(context, apkFilePath);
}
}
}
@OnClick(R.id.download_button)
public void downloadImage() {
String imageUrl = imageUrlList.get(imageViewPager.getCurrentItem());
String fileName = StringUtils.getImageNameFromUrl(imageUrl);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/scallop";
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(fileName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(path, fileName);
downloadManager.enqueue(request);
}
/**
* 下载文件
*/
@SuppressLint("NewApi")
private void startDownload() {
mDownloadObserver = new DownloadObserver(new Handler());
getContentResolver().registerContentObserver(
Uri.parse("content://downloads/my_downloads"), true,
mDownloadObserver);
mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//将含有中文的url进行encode
String fileUrl = toUtf8String(mFileUrl);
try {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(fileUrl));
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, mFileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
mRequestId = mDownloadManager.enqueue(request);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
long localDownloadId = UpdaterUtils.getLocalDownloadId(context);
if (downloadApkId == localDownloadId) {
Logger.get().d("download complete. downloadId is " + downloadApkId);
installApk(context, downloadApkId);
}
} else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
//处理 如果还未完成下载,用户点击Notification
Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(viewDownloadIntent);
}
}
@Nullable
public Download getDownload(long downloadId) {
Download download = null;
if (mDownloadManager != null) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = mDownloadManager.query(query);
if (c != null) {
if (c.moveToFirst()) {
download = Download.from(c);
}
c.close();
}
}
return download;
}
public List<Download> getDownloads() {
List<Download> downloads = new ArrayList<>();
if (mDownloadManager != null) {
DownloadManager.Query query = new DownloadManager.Query();
Cursor c = mDownloadManager.query(query);
if (c != null) {
while (c.moveToNext()) {
downloads.add(Download.from(c));
}
c.close();
}
}
return downloads;
}
private void downloadEnvironment(@NonNull String envId) {
final Environment environment = EnvironmentUtils.getExternalEnvironmentById(mContext, envId);
if (environment != null) {
// Check if the env is being downloaded
boolean isDownloading = mDownloadManager.getDownloads().stream()
.filter(item ->
item.getStatus() == DownloadManager.STATUS_RUNNING &&
item.getStatus() == DownloadManager.STATUS_PAUSED &&
item.getStatus() == DownloadManager.STATUS_PENDING &&
item.getUri().equals(environment.getPayload()))
.findFirst().orElse(null) != null;
if (!isDownloading) {
// If the env is not being downloaded, start downloading it
DownloadJob job = DownloadJob.create(environment.getPayload());
mDownloadManager.startDownload(job);
}
}
}
/**
* Downloads an given Moodle item into the user's device.
* @param item the item to be downloaded.
*/
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void downloadMoodleObject(MoodleModuleContent item) {
String url = item.getFileurl() + "&token=" + ApplicationManager.userCredentials.getMoodleToken();
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, item.getFilename());
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
MimeTypeMap mimetype = MimeTypeMap.getSingleton();
String extension = FilenameUtils.getExtension(item.getFilename());
request.setMimeType(mimetype.getMimeTypeFromExtension(extension));
dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
enqueue = dm.enqueue(request);
}
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case DownloadManager.ACTION_NOTIFICATION_CLICKED:
openDownload(context, intent);
break;
case DownloadNotificationService.ACTION_DOWNLOAD_RESUME:
case DownloadNotificationService.ACTION_DOWNLOAD_CANCEL:
case DownloadNotificationService.ACTION_DOWNLOAD_PAUSE:
case DownloadNotificationService.ACTION_DOWNLOAD_OPEN:
performDownloadOperation(context, intent);
break;
default:
break;
}
}
public static void downloadFile(Context context, String url, long id) {
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.addRequestHeader("droidddle", "1.1");
File file = getDownloadFile(context, url, id);
Uri destination = Uri.fromFile(file);
if (file.exists()) {
file.delete();
}
request.setDestinationUri(destination);
// request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
// path);
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle(file.getName());
request.setVisibleInDownloadsUi(true);
long downId = mgr.enqueue(request);
String tips = context
.getString(R.string.download_tips, file.getParentFile().getAbsolutePath());
showToast(context, tips);
}
/**
* Check the external storage and notify user on error.
*
* @param fullDirPath The dir path to download a file. Normally this is external storage.
* @param externalStorageStatus The status of the external storage.
* @return Whether external storage is ok for downloading.
*/
private boolean checkExternalStorageAndNotify(
String filename, File fullDirPath, String externalStorageStatus) {
if (fullDirPath == null) {
Log.e(TAG, "Download failed: no SD card");
alertDownloadFailure(
filename, DownloadManager.ERROR_DEVICE_NOT_FOUND);
return false;
}
if (!externalStorageStatus.equals(Environment.MEDIA_MOUNTED)) {
int reason = DownloadManager.ERROR_DEVICE_NOT_FOUND;
// Check to see if the SDCard is busy, same as the music app
if (externalStorageStatus.equals(Environment.MEDIA_SHARED)) {
Log.e(TAG, "Download failed: SD card unavailable");
reason = DownloadManager.ERROR_FILE_ERROR;
} else {
Log.e(TAG, "Download failed: no SD card");
}
alertDownloadFailure(filename, reason);
return false;
}
return true;
}
protected void pollDownloadManager() {
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = downloadManager.query(q);
cursor.moveToFirst();
final int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final String msg = PROGRESS_MSG + ((double)bytesDownloaded) / 1000000.0 + " MB";
publishProgress(msg);
status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
statusMessage = statusMessage(cursor, bytesDownloaded);
Log.d("OSMDownloader", statusMessage);
if (status != DownloadManager.STATUS_PENDING && status != DownloadManager.STATUS_RUNNING) {
downloading = false;
}
// throttle the thread
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public Cursor queryChildDocumentsForManage(
String parentDocumentId, String[] projection, String sortOrder)
throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
cursor = mDm.query(
new DownloadManager.Query());//.setOnlyIncludeVisibleInDownloadsUi(true));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
private void registerReceiver(){
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadCompleteReceiver, filter);
IntentFilter filterReceiver = new IntentFilter(ActionManager.ACTION_FILE_CHANGED);
registerReceiver(fileChangeReceiver, filterReceiver);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = getContext2();
if (null != context && null != mTorrentList && position < mTorrentList.length) {
String url = mTorrentList[position].first;
String name = mTorrentList[position].second;
// Use system download service
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url));
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
FileUtils.sanitizeFilename(name + ".torrent"));
r.allowScanningByMediaScanner();
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
r.addRequestHeader("Cookie", EhApplication.getEhCookieStore(context).getCookieHeader(HttpUrl.get(url)));
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
if (dm != null) {
try {
dm.enqueue(r);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
}
}
}
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
@Override
public synchronized int getAverageProgressForDownloads(long[] dmids) {
//Need to check first if the download manager service is enabled
if(!isDownloadManagerEnabled())
return 0;
Query query = new Query();
query.setFilterById(dmids);
try {
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int count = c.getCount();
float aggrPercent = 0;
do {
long downloaded = c
.getLong(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long size = c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
aggrPercent += (100f * downloaded / size);
} while (c.moveToNext());
c.close();
int average = (int) (aggrPercent / count);
return average;
}
c.close();
}catch (Exception ex){
logger.debug(ex.getMessage());
}
return 0;
}
/**
* Called when android DownloadManager fails to download the content.
*
* @param downloadInfo The information about the download.
* @param downloadId Download Id from the Android DownloadManager.
* @param reason The reason of failure.
* @param notifyURI The previously saved installNotifyURI attribute.
*/
public void onDownloadFailed(
DownloadInfo downloadInfo, long downloadId, int reason, String notifyURI) {
String status = DOWNLOAD_STATUS_DEVICE_ABORTED;
switch (reason) {
case DownloadManager.ERROR_CANNOT_RESUME:
status = DOWNLOAD_STATUS_LOSS_OF_SERVICE;
break;
case DownloadManager.ERROR_HTTP_DATA_ERROR:
case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
status = DOWNLOAD_STATUS_LOADER_ERROR;
break;
case DownloadManager.ERROR_INSUFFICIENT_SPACE:
status = DOWNLOAD_STATUS_INSUFFICIENT_MEMORY;
break;
default:
break;
}
OMAInfo omaInfo = mPendingOMADownloads.get(downloadId);
if (omaInfo == null) {
// Just send the notification in this case.
omaInfo = new OMAInfo();
omaInfo.addAttributeValue(OMA_INSTALL_NOTIFY_URI, notifyURI);
sendInstallNotificationAndNextStep(omaInfo, downloadInfo, downloadId, status);
return;
}
showDownloadWarningDialog(
R.string.oma_download_failed, omaInfo, downloadInfo, status);
mPendingOMADownloads.remove(downloadId);
}
@Override
protected void onPostExecute(Boolean success) {
DownloadManager manager =
(DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
if (success) {
String path = mDownloadInfo.getFilePath();
if (!TextUtils.isEmpty(path)) {
// Move the downloaded content from the app directory to public directory.
File fromFile = new File(path);
String fileName = fromFile.getName();
File toFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), fileName);
if (fromFile.renameTo(toFile)) {
manager.addCompletedDownload(
fileName, mDownloadInfo.getDescription(), false,
mDownloadInfo.getMimeType(), toFile.getPath(),
mDownloadInfo.getBytesReceived(), true);
} else if (fromFile.delete()) {
Log.w(TAG, "Failed to rename the file.");
return;
} else {
Log.w(TAG, "Failed to rename and delete the file.");
}
}
showNextUrlDialog(mOMAInfo);
} else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
// Remove the downloaded content.
manager.remove(mDownloadId);
}
}
protected boolean downloadInProgress() {
long downloadId = getDownloadID();
if (downloadId == -1) {
return false;
}
try {
switch (getDownloadManagerStatus(downloadId)) {
case DownloadManager.STATUS_FAILED:
removeCurrentDownloadReferences();
return false;
case DownloadManager.STATUS_SUCCESSFUL:
removeCurrentDownloadReferences();
return false;
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_PAUSED:
case DownloadManager.STATUS_RUNNING:
return true;
default:
case -1:
return false;
}
}
catch (Exception ex) {
logger.error("Could not process download ID [{}]", downloadId, ex);
}
return false;
}