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 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 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; }
@Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); Query query = new Query(); query.setFilterById(downloadId); Cursor c = dm.query(query); while (c.moveToNext()) { int columnIndex = c .getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c .getInt(columnIndex)) { // We've finished all downloads; stopdownloadbutton.setVisibility(View.GONE); } } } }
public static HashMap<Long,String> getCurrentDownloads(Context ctx) { HashMap<Long,String> res = new HashMap<Long,String>(); DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE); Query query = new DownloadManager.Query(); if(query!=null) { query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PAUSED|DownloadManager.STATUS_SUCCESSFUL| DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_PENDING); } Cursor c = dm.query(query); while (c.moveToNext()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); if (status == DownloadManager.STATUS_PAUSED || status == DownloadManager.STATUS_RUNNING) { res.put(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)), c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE))); } } return res; }
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); }
@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()) { includeTransferFromCursor(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 { cursor = mDm.query(new DownloadManager.Query().setOnlyIncludeVisibleInDownloadsUi(true) .setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL)); copyNotificationUri(result, cursor); while (cursor.moveToNext()) { includeTransferFromCursor(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()) { includeTransferFromCursor(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; }
/** * 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. } }
/** * Initialises download manager for GINGERBREAD and newer */ @SuppressLint("NewApi") private void initDownloadManager() { mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); mReceiver = new BroadcastReceiver() { @SuppressLint("NewApi") @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); final Query query = new Query(); query.setFilterById(downloadId); final Cursor c = mDownloadManager.query(query); if (c.moveToFirst()) { final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { // we're not checking download id here, that is done in handleDownloads final String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); handleDownloads(uriString); } } } } }; registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
@Override public synchronized NativeDownloadModel getDownload(long dmid) { //Need to check first if the download manager service is enabled if(!isDownloadManagerEnabled()) return null; try { Query query = new Query(); query.setFilterById(dmid); Cursor c = dm.query(query); if (c.moveToFirst()) { long downloaded = c .getLong(c .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); long size = c.getLong(c .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); String filepath = c.getString(c .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); int status = c.getInt(c .getColumnIndex(DownloadManager.COLUMN_STATUS)); c.close(); NativeDownloadModel ndm = new NativeDownloadModel(); ndm.dmid = dmid; ndm.downloaded = downloaded; ndm.size = size; ndm.filepath = filepath; ndm.status = status; return ndm; } c.close(); } catch(Exception e) { logger.error(e); } return 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; }
/** * Initialises download manager for GINGERBREAD and newer */ private void initDownloadManager() { mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); mReceiver = new BroadcastReceiver() { @SuppressLint("NewApi") @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); final Query query = new Query(); query.setFilterById(downloadId); final Cursor c = mDownloadManager.query(query); if (c.moveToFirst()) { final int statusCol = c.getColumnIndex(DownloadManager.COLUMN_STATUS); final int reasonCol = c.getColumnIndex(DownloadManager.COLUMN_REASON); Log.i(TAG, "Download status:" + c.getInt(statusCol)); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(statusCol)) { // we're not checking download id here, that is done in handleDownloads final String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); handleDownloads(uriString); } else if (DownloadManager.STATUS_FAILED == c.getInt(statusCol)) { Log.e(TAG, "Download failed:" + c.getString(reasonCol)); } } } } }; registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
@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(); } } } } }
private void downloadCompleted(Context context, Intent intent) { //Files are ready String filename = context.getString(R.string.hs_attachment); String filepath = null; String mediaType = null; DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); StringBuilder text = new StringBuilder(); Query query = new Query(); query.setFilterById(downloadId); Cursor c = dm.query(query); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE)); filepath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)); if (status == DownloadManager.STATUS_SUCCESSFUL) { text.append(context.getString(R.string.hs_download_complete)); } else { text.append(context.getString(R.string.hs_error_during_download)); } } NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setAutoCancel(true); notificationBuilder.setContentText(text.toString()); notificationBuilder.setContentTitle(filename); notificationBuilder.setSmallIcon(R.drawable.hs_download_light); notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); notificationBuilder.setContentIntent(getPendingIntent(context)); notificationManager.notify(filename, NOTIFICATION_ID, notificationBuilder.build()); }
@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(); } }
private void registerDownloadReceiver() { if (mReceiver != null) return; mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (mDownloadId == -1) return; // Not waiting for download, ignore if (!DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) return; // Only interested in completed downloads Query query = new Query(); query.setFilterById(mDownloadId); Cursor c = mDownloadManager.query(query); if (c.moveToFirst()) { if (DownloadManager.STATUS_SUCCESSFUL != c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) return; // Only interested in successful downloads Uri localUri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))); if (!mState.hasKeys()) { importKeys(localUri); } else { importKeysWithConfirmation(localUri); } mDownloadId = -1; } } }; registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
/** 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)); }