下面列出了怎么用android.app.DownloadManager.Query的API类实例代码及写法,或者点击链接到github查看源代码。
private static void removeAllForUrl(Context context, String url) {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = dm.query(new Query());
int columnId = c.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
List<Long> idsList = new ArrayList<>(1);
while (c.moveToNext()) {
if (url.equals(c.getString(columnUri)))
idsList.add(c.getLong(columnId));
}
c.close();
if (idsList.isEmpty())
return;
long[] ids = new long[idsList.size()];
for (int i = 0; i < ids.length; i++)
ids[i] = idsList.get(i);
dm.remove(ids);
}
@Override
public Cursor queryDocument(String docId, String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
if (DOC_ID_ROOT.equals(docId)) {
includeDefaultDocument(result);
} else {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
cursor = mDm.query(new Query().setFilterById(Long.parseLong(docId)));
//copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
}
return result;
}
@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 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;
}
@Override
public Cursor queryDocument(String docId, String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
if (DOC_ID_ROOT.equals(docId)) {
includeDefaultDocument(result);
} else {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
cursor = mDm.query(new Query().setFilterById(Long.parseLong(docId)));
//copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
}
return result;
}
@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 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;
}
@Override
public Cursor queryDocument(String docId, String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
if (DOC_ID_ROOT.equals(docId)) {
includeDefaultDocument(result);
} else {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
cursor = mDm.query(new Query().setFilterById(Long.parseLong(docId)));
//copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
}
return result;
}
@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 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 int getProgressPercentage() {
int downloadedBytesSoFar = 0, totalBytes = 0, percentage = 0;
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try {
Cursor c = dm.query(new DownloadManager.Query().setFilterById(enqueue));
if (c.moveToFirst()) {
int soFarIndex =c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
downloadedBytesSoFar = (int) c.getLong(soFarIndex);
int totalSizeIndex = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
totalBytes = (int) c.getLong(totalSizeIndex);
}
System.out.println("PERCEN ------" + downloadedBytesSoFar
+ " ------ " + totalBytes + "****" + percentage);
percentage = (downloadedBytesSoFar * 100 / totalBytes);
System.out.println("percentage % " + percentage);
} catch (Exception e) {
e.printStackTrace();
}
return percentage;
}
@Override
public synchronized NativeDownloadModel getProgressDetailsForDownloads(long[] dmids) {
//Need to check first if the download manager service is enabled
if (!isDownloadManagerEnabled()) return null;
final NativeDownloadModel downloadProgressModel = new NativeDownloadModel();
final Query query = new Query();
query.setFilterById(dmids);
final Cursor c = dm.query(query);
if (c.moveToFirst()) {
downloadProgressModel.downloadCount = c.getCount();
do {
downloadProgressModel.downloaded += c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
downloadProgressModel.size += c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
} while (c.moveToNext());
c.close();
return downloadProgressModel;
}
c.close();
return null;
}
@Override
public synchronized boolean isDownloadComplete(long dmid) {
//Need to check first if the download manager service is enabled
if(!isDownloadManagerEnabled())
return false;
Query query = new Query();
query.setFilterById(dmid);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
c.close();
return (status == DownloadManager.STATUS_SUCCESSFUL);
}
c.close();
return false;
}
public void onResume() {
super.onResume();
downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_URI);
String urlDownloaded = c.getString(columnIndex);
if ((issue.getPdfUrl() + "/").equals(urlDownloaded)) {
menu.findItem(R.id.menu_view).setVisible(true);
menu.findItem(R.id.menu_cancel_download).setVisible(false);
}
}
c.close();
}
}
};
getActivity().registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private void cancelDownload() {
Query query = new Query();
query.setFilterByStatus(
DownloadManager.STATUS_PAUSED|
DownloadManager.STATUS_PENDING|
DownloadManager.STATUS_RUNNING);
Cursor cur = dm.query(query);
int col = cur.getColumnIndex(DownloadManager.COLUMN_URI);
int colId = cur.getColumnIndex(DownloadManager.COLUMN_ID);
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
if(issue.getPdfUrl().equals(cur.getString(col)))
dm.remove(cur.getLong(colId));
}
cur.close();
menu.findItem(R.id.menu_view).setVisible(true);
menu.findItem(R.id.menu_cancel_download).setVisible(false);
}
/**
* Retrieve information about a specific download from DownloadManager.
*/
private static CompletedDownloadInfo getCompletedDownloadInfo(
final DownloadManagerWrapper manager, final long downloadId) {
final Query query = new Query().setFilterById(downloadId);
final Cursor cursor = manager.query(query);
if (null == cursor) {
return new CompletedDownloadInfo(null, downloadId, DownloadManager.STATUS_FAILED);
}
try {
final String uri;
final int status;
if (cursor.moveToNext()) {
final int columnStatus = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int columnError = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
final int columnUri = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
final int error = cursor.getInt(columnError);
status = cursor.getInt(columnStatus);
final String uriWithAnchor = cursor.getString(columnUri);
int anchorIndex = uriWithAnchor.indexOf('#');
if (anchorIndex != -1) {
uri = uriWithAnchor.substring(0, anchorIndex);
} else {
uri = uriWithAnchor;
}
if (DownloadManager.STATUS_SUCCESSFUL != status) {
Log.e(TAG, "Permanent failure of download " + downloadId
+ " with error code: " + error);
}
} else {
uri = null;
status = DownloadManager.STATUS_FAILED;
}
return new CompletedDownloadInfo(uri, downloadId, status);
} finally {
cursor.close();
}
}
@Override
public void run() {
try {
final UpdateHelper updateHelper = new UpdateHelper();
final Query query = new Query().setFilterById(mId);
setIndeterminate(true);
while (!isInterrupted()) {
final Cursor cursor = mDownloadManagerWrapper.query(query);
if (null == cursor) {
// Can't contact DownloadManager: this should never happen.
return;
}
try {
if (cursor.moveToNext()) {
final int columnBytesDownloadedSoFar = cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
final int bytesDownloadedSoFar =
cursor.getInt(columnBytesDownloadedSoFar);
updateHelper.setProgressFromAnotherThread(bytesDownloadedSoFar);
} else {
// Download has finished and DownloadManager has already been asked to
// clean up the db entry.
updateHelper.setProgressFromAnotherThread(getMax());
return;
}
} finally {
cursor.close();
}
Thread.sleep(REPORT_PERIOD);
}
} catch (InterruptedException e) {
// Do nothing and terminate normally.
}
}
public static DownloadInfo getById(Context context, long id) {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = dm.query(new Query().setFilterById(id));
if (!c.moveToFirst()) {
c.close();
return null;
}
int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
int columnTitle = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
int columnLastMod = c.getColumnIndexOrThrow(
DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
int columnLocalUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
int columnStatus = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
int columnTotalSize = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
int columnBytesDownloaded = c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
int columnReason = c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
int status = c.getInt(columnStatus);
String localFilename;
try {
localFilename = getFilenameFromUri(c.getString(columnLocalUri));
} catch (UnsupportedOperationException e) {
Toast.makeText(context, "An error occurred. Restart app and try again.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
if (status == DownloadManager.STATUS_SUCCESSFUL && !new File(localFilename).isFile()) {
dm.remove(id);
c.close();
return null;
}
DownloadInfo info = new DownloadInfo(id, c.getString(columnUri),
c.getString(columnTitle), c.getLong(columnLastMod),
localFilename, status,
c.getInt(columnTotalSize), c.getInt(columnBytesDownloaded),
c.getInt(columnReason));
c.close();
return info;
}
/**
* Retrieve information about a specific download from DownloadManager.
*/
private static CompletedDownloadInfo getCompletedDownloadInfo(
final DownloadManagerWrapper manager, final long downloadId) {
final Query query = new Query().setFilterById(downloadId);
final Cursor cursor = manager.query(query);
if (null == cursor) {
return new CompletedDownloadInfo(null, downloadId, DownloadManager.STATUS_FAILED);
}
try {
final String uri;
final int status;
if (cursor.moveToNext()) {
final int columnStatus = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int columnError = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
final int columnUri = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
final int error = cursor.getInt(columnError);
status = cursor.getInt(columnStatus);
final String uriWithAnchor = cursor.getString(columnUri);
int anchorIndex = uriWithAnchor.indexOf('#');
if (anchorIndex != -1) {
uri = uriWithAnchor.substring(0, anchorIndex);
} else {
uri = uriWithAnchor;
}
if (DownloadManager.STATUS_SUCCESSFUL != status) {
Log.e(TAG, "Permanent failure of download " + downloadId
+ " with error code: " + error);
}
} else {
uri = null;
status = DownloadManager.STATUS_FAILED;
}
return new CompletedDownloadInfo(uri, downloadId, status);
} finally {
cursor.close();
}
}
@Override
public void run() {
try {
final UpdateHelper updateHelper = new UpdateHelper();
final Query query = new Query().setFilterById(mId);
setIndeterminate(true);
while (!isInterrupted()) {
final Cursor cursor = mDownloadManagerWrapper.query(query);
if (null == cursor) {
// Can't contact DownloadManager: this should never happen.
return;
}
try {
if (cursor.moveToNext()) {
final int columnBytesDownloadedSoFar = cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
final int bytesDownloadedSoFar =
cursor.getInt(columnBytesDownloadedSoFar);
updateHelper.setProgressFromAnotherThread(bytesDownloadedSoFar);
} else {
// Download has finished and DownloadManager has already been asked to
// clean up the db entry.
updateHelper.setProgressFromAnotherThread(getMax());
return;
}
} finally {
cursor.close();
}
Thread.sleep(REPORT_PERIOD);
}
} catch (InterruptedException e) {
// Do nothing and terminate normally.
}
}
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
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)
.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext() && result.getCount() < 12) {
final String mimeType = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE));
final String uri = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIAPROVIDER_URI));
// Skip images that have been inserted into the MediaStore so we
// don't duplicate them in the recents list.
if (mimeType == null
|| (mimeType.startsWith("image/") && !TextUtils.isEmpty(uri))) {
continue;
}
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
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)
.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext() && result.getCount() < 12) {
final String mimeType = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE));
final String uri = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIAPROVIDER_URI));
// Skip images that have been inserted into the MediaStore so we
// don't duplicate them in the recents list.
if (mimeType == null
|| (mimeType.startsWith("image/") && !TextUtils.isEmpty(uri))) {
continue;
}
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
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)
.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
//copyNotificationUri(result, cursor);
while (cursor.moveToNext() && result.getCount() < 12) {
final String mimeType = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE));
final String uri = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIAPROVIDER_URI));
// Skip images that have been inserted into the MediaStore so we
// don't duplicate them in the recents list.
if (mimeType == null
|| (mimeType.startsWith("image/") && !TextUtils.isEmpty(uri))) {
continue;
}
includeDownloadFromCursor(result, cursor);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
public static int getDownloadStatus(Context context, long enqueueId)
{
Query query = new Query();
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
query.setFilterById(enqueueId);
Cursor c = dm.query(query);
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
return c.getInt(columnIndex);
}
return -1; // Aborted.
}
@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;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
synchronized (currentDownloads) {
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)
&& !currentDownloads.isEmpty()) {
// long downloadId = intent.getLongExtra(
// DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
long[] downloads = new long[currentDownloads.size()];
for (int i = 0, len = currentDownloads.size(); i < len; i++) {
downloads[i] = currentDownloads.get(i);
}
query.setFilterById(downloads);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
Cursor cursor = mDownloadManager.query(query);
boolean pluginAdded = false;
if (cursor.moveToFirst()) {
int columnId = cursor
.getColumnIndex(DownloadManager.COLUMN_ID);
do {
currentDownloads.remove(cursor.getLong(columnId));
pluginAdded = true;
} while (cursor.moveToNext());
if (pluginAdded) {
PluginLoader.reloadPlugins();
}
}
}
}
}
/**
* Retrieve information about a specific download from DownloadManager.
*/
private static CompletedDownloadInfo getCompletedDownloadInfo(
final DownloadManagerWrapper manager, final long downloadId) {
final Query query = new Query().setFilterById(downloadId);
final Cursor cursor = manager.query(query);
if (null == cursor) {
return new CompletedDownloadInfo(null, downloadId, DownloadManager.STATUS_FAILED);
}
try {
final String uri;
final int status;
if (cursor.moveToNext()) {
final int columnStatus = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int columnError = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
final int columnUri = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
final int error = cursor.getInt(columnError);
status = cursor.getInt(columnStatus);
final String uriWithAnchor = cursor.getString(columnUri);
int anchorIndex = uriWithAnchor.indexOf('#');
if (anchorIndex != -1) {
uri = uriWithAnchor.substring(0, anchorIndex);
} else {
uri = uriWithAnchor;
}
if (DownloadManager.STATUS_SUCCESSFUL != status) {
Log.e(TAG, "Permanent failure of download " + downloadId
+ " with error code: " + error);
}
} else {
uri = null;
status = DownloadManager.STATUS_FAILED;
}
return new CompletedDownloadInfo(uri, downloadId, status);
} finally {
cursor.close();
}
}
@Override
public void run() {
try {
final UpdateHelper updateHelper = new UpdateHelper();
final Query query = new Query().setFilterById(mId);
setIndeterminate(true);
while (!isInterrupted()) {
final Cursor cursor = mDownloadManagerWrapper.query(query);
if (null == cursor) {
// Can't contact DownloadManager: this should never happen.
return;
}
try {
if (cursor.moveToNext()) {
final int columnBytesDownloadedSoFar = cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
final int bytesDownloadedSoFar =
cursor.getInt(columnBytesDownloadedSoFar);
updateHelper.setProgressFromAnotherThread(bytesDownloadedSoFar);
} else {
// Download has finished and DownloadManager has already been asked to
// clean up the db entry.
updateHelper.setProgressFromAnotherThread(getMax());
return;
}
} finally {
cursor.close();
}
Thread.sleep(REPORT_PERIOD);
}
} catch (InterruptedException e) {
// Do nothing and terminate normally.
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int titleColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
String title = context.getString(R.string.menu_view) + " " + c.getString(titleColumnIndex);
int pdfPathColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
String pdfPath = c.getString(pdfPathColumnIndex);
Intent intentPdf = new Intent(Intent.ACTION_VIEW);
intentPdf.setDataAndType(Uri.parse(pdfPath), "application/pdf");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
intentPdf, PendingIntent.FLAG_CANCEL_CURRENT);
SharedPreferences settings = context.getSharedPreferences("IssueDownloadNotification", Context.MODE_PRIVATE);
if(settings.getBoolean(title, false))
return;
settings.edit().putBoolean(title, true).commit();
Notification noti = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(context.getString(R.string.download_completed_text))
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.new_issue)
.getNotification();
PebbleNotifier.notify(context, title, context.getString(R.string.download_completed_text));
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(ID_NOTIFICATION++, noti);
}
c.close();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}