List of usage examples for android.app DownloadManager query
public Cursor query(Query query)
From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java
private Boolean checkDownloadCompleted(long id) { DownloadManager mgr = (DownloadManager) this.cordova.getActivity() .getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id);//ww w .ja va 2 s. co m Cursor cur = mgr.query(query); int idxStatus = cur.getColumnIndex(DownloadManager.COLUMN_STATUS); int idxURI = cur.getColumnIndex(DownloadManager.COLUMN_URI); if (cur.moveToFirst()) { int status = cur.getInt(idxStatus); String uri = cur.getString(idxURI); Download curDownload = activDownloads.get(uri); if (status == DownloadManager.STATUS_SUCCESSFUL) { // TODO review what else we can have here copyTempFileToActualFile(curDownload); CleanUp(curDownload); return true; } } cur.close(); return false; }
From source file:com.concentricsky.android.khanacademy.data.KADataService.java
private void updateDownloadStatus(Intent intent, final PendingIntent pendingIntent, final int startId) { final long id = intent.getLongExtra(EXTRA_ID, -1); final DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); final DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(id);/*from w w w.j a v a 2s. c o m*/ new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... arg) { Cursor cursor = mgr.query(q); String youtubeId = null; int status = -1; if (cursor.moveToFirst()) { String filename = cursor .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); youtubeId = OfflineVideoManager.youtubeIdFromFilename(filename); status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); } cursor.close(); if (status == DownloadManager.STATUS_SUCCESSFUL && youtubeId != null) { try { Dao<Video, String> videoDao = helper.getVideoDao(); UpdateBuilder<Video, String> q = videoDao.updateBuilder(); q.where().eq("youtube_id", youtubeId); q.updateColumnValue("download_status", Video.DL_STATUS_COMPLETE); q.update(); return true; } catch (SQLException e) { e.printStackTrace(); } } return false; } @Override protected void onPostExecute(Boolean successful) { if (successful) { broadcastOfflineVideoSetChanged(); finish(startId, pendingIntent, RESULT_SUCCESS); } else { finish(startId, pendingIntent, RESULT_ERROR); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java
private long findActiveDownload(String uri) { DownloadManager mgr = (DownloadManager) cordova.getActivity().getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = DOWNLOAD_ID_UNDEFINED; DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_SUCCESSFUL); Cursor cur = mgr.query(query); int idxId = cur.getColumnIndex(DownloadManager.COLUMN_ID); int idxUri = cur.getColumnIndex(DownloadManager.COLUMN_URI); for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { if (uri.equals(cur.getString(idxUri))) { downloadId = cur.getLong(idxId); break; }/* w ww .j a v a2 s .c o m*/ } cur.close(); return downloadId; }
From source file:de.escoand.readdaily.DownloadHandler.java
@Override public void onReceive(final Context context, final Intent intent) { final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); final Database db = Database.getInstance(context); final Cursor downloads = db.getDownloads(); LogHandler.log(Log.WARN, "receive starting"); while (downloads.moveToNext()) { final long id = downloads.getLong(downloads.getColumnIndex(Database.COLUMN_ID)); final String name = downloads.getString(downloads.getColumnIndex(Database.COLUMN_SUBSCRIPTION)); final String mime = downloads.getString(downloads.getColumnIndex(Database.COLUMN_TYPE)); final Cursor download = manager.query(new DownloadManager.Query().setFilterById(id)); // download exists if (!download.moveToFirst()) continue; // download finished if (download.getInt( download.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL) continue; // import file in background new Thread(new Runnable() { @Override//w w w. j av a 2s. co m public void run() { try { LogHandler.log(Log.WARN, "import starting of " + name); final FileInputStream stream = new ParcelFileDescriptor.AutoCloseInputStream( manager.openDownloadedFile(id)); final String mimeServer = manager.getMimeTypeForDownloadedFile(id); LogHandler.log(Log.INFO, "id: " + String.valueOf(id)); LogHandler.log(Log.INFO, "manager: " + manager.toString()); LogHandler.log(Log.INFO, "stream: " + stream.toString()); LogHandler.log(Log.INFO, "mime: " + mime); LogHandler.log(Log.INFO, "mimeServer: " + mimeServer); switch (mime != null ? mime : (mimeServer != null ? mimeServer : "")) { // register feedback case "application/json": final byte[] buf = new byte[256]; final int len = stream.read(buf); LogHandler.log(Log.WARN, "register feedback: " + new String(buf, 0, len)); break; // csv data case "text/plain": db.importCSV(name, stream); break; // xml data case "application/xml": case "text/xml": db.importXML(name, stream); break; // zipped data case "application/zip": db.importZIP(name, stream); break; // do nothing default: LogHandler.log(new IntentFilter.MalformedMimeTypeException()); break; } stream.close(); LogHandler.log(Log.WARN, "import finished (" + name + ")"); } // file error catch (FileNotFoundException e) { LogHandler.logAndShow(e, context, R.string.message_download_open); } // stream error catch (IOException e) { LogHandler.logAndShow(e, context, R.string.message_download_read); } // xml error catch (XmlPullParserException e) { LogHandler.logAndShow(e, context, R.string.message_download_xml); } // clean finally { manager.remove(id); db.removeDownload(id); LogHandler.log(Log.WARN, "clean finished"); } } }).start(); } downloads.close(); LogHandler.log(Log.WARN, "receiving done"); }
From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java
private void StartProgressTracking(final Download curDownload) { // already started if (curDownload.getTimerProgressUpdate() != null) { return;//from w ww.j a v a2 s. c o m } final DownloadManager mgr = (DownloadManager) this.cordova.getActivity() .getSystemService(Context.DOWNLOAD_SERVICE); curDownload.setTimerProgressUpdate(new Timer()); curDownload.getTimerProgressUpdate().schedule(new TimerTask() { @Override public void run() { DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(curDownload.getDownloadId()); Cursor cursor = mgr.query(q); if (cursor.moveToFirst()) { long bytesDownloaded = cursor .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); long bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); if (bytesTotal != -1) { Log.d("BackgroundDownload", "DOWNLOAD STARTED for " + curDownload.getDownloadId()); try { JSONObject jsonProgress = new JSONObject(); jsonProgress.put("bytesReceived", bytesDownloaded); jsonProgress.put("totalBytesToReceive", bytesTotal); JSONObject obj = new JSONObject(); obj.put("progress", jsonProgress); PluginResult progressUpdate = new PluginResult(PluginResult.Status.OK, obj); progressUpdate.setKeepCallback(true); curDownload.getCallbackContextDownloadStart().sendPluginResult(progressUpdate); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { long status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); long reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)); Log.d("BackgroundDownload", "download not started for " + curDownload.getTempFilePath() + " (status " + status + ") (reason " + reason + ")"); } } cursor.close(); } }, DOWNLOAD_PROGRESS_UPDATE_TIMEOUT, DOWNLOAD_PROGRESS_UPDATE_TIMEOUT); }
From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java
private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) { String destFile;/*from w w w .j a va 2 s .com*/ try { destFile = new File(new URL(downloadUrl).getPath()).getName(); } catch (MalformedURLException e) { throw new RuntimeException("Invalid download URL!", e); } DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); final DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus( DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); final Cursor cursor = downloadManager.query(query); // Due to a bug, cursor is null instead of empty when // the download manager is disabled. if (cursor == null) { new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error)) .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed)) .setNeutralButton("Close", null).show(); return; } while (cursor.moveToNext()) { if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)))) break; if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)))) break; } if (!cursor.isAfterLast()) { downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID))); downloadButton.setText(getString(R.string.downloadButton, bytes / 1024.0 / 1024.0)); cursor.close(); return; } cursor.close(); Request request = new Request(Uri.parse(downloadUrl)); Log.d(LOG, "Downloading to: " + destFile); request.setTitle(destFile); File destFilePath = new File(application.getDictDir(), destFile); destFilePath.delete(); try { request.setDestinationUri(Uri.fromFile(destFilePath)); } catch (Exception e) { } try { downloadManager.enqueue(request); } catch (SecurityException e) { request = new Request(Uri.parse(downloadUrl)); request.setTitle(destFile); downloadManager.enqueue(request); } Log.w(LOG, "Download started: " + destFile); downloadButton.setText("X"); }
From source file:org.chromium.chrome.browser.download.DownloadManagerService.java
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) return;//from w ww .j a v a 2 s . c o m final DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (downloadId == -1) return; boolean isPendingOMADownload = mOMADownloadHandler.isPendingOMADownload(downloadId); boolean isInOMASharedPrefs = isDownloadIdInOMASharedPrefs(downloadId); if (isPendingOMADownload || isInOMASharedPrefs) { clearPendingOMADownload(downloadId, null); mPendingAutoOpenDownloads.remove(downloadId); } else if (mPendingAutoOpenDownloads.get(downloadId) != null) { Cursor c = manager.query(new DownloadManager.Query().setFilterById(downloadId)); int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); while (c.moveToNext()) { int status = c.getInt(statusIndex); DownloadInfo info = mPendingAutoOpenDownloads.get(downloadId); switch (status) { case DownloadManager.STATUS_SUCCESSFUL: try { mPendingAutoOpenDownloads.remove(downloadId); if (OMADownloadHandler.OMA_DOWNLOAD_DESCRIPTOR_MIME.equalsIgnoreCase(info.getMimeType())) { mOMADownloadHandler.handleOMADownload(info, downloadId); manager.remove(downloadId); break; } Uri uri = manager.getUriForDownloadedFile(downloadId); Intent launchIntent = new Intent(Intent.ACTION_VIEW); launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(downloadId)); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(launchIntent); } catch (ActivityNotFoundException e) { Log.w(TAG, "Activity not found."); } break; case DownloadManager.STATUS_FAILED: mPendingAutoOpenDownloads.remove(downloadId); break; default: break; } } } if (mPendingAutoOpenDownloads.size() == 0) { mContext.unregisterReceiver(this); } }
From source file:jupiter.broadcasting.live.holo.JBPlayer.java
public void DownLoad(String url) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); String ver = (av == 0) ? getString(R.string.audio) : getString(R.string.video); request.setDescription(getString(R.string.progress) + "(" + ver + ")..."); request.setTitle(getIntent().getStringExtra("title")); down.setClickable(false);//w w w . ja v a2s .c om // in order for this if to run, you must use the android 3.2 to compile your app if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } String ext = (av == 0) ? "mp3" : "mp4"; request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PODCASTS + "/JB", getIntent().getStringExtra("title") + "." + ext); // get download service and enqueue file final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); final long enqueue = manager.enqueue(request); //register receiver to be notified when download finishes BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(enqueue); Cursor c = manager.query(query); if (c != null) { if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { Toast.makeText(getBaseContext(), "Finished", Toast.LENGTH_LONG).show(); hasit = true; down.setClickable(true); } } } } } }; registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
From source file:com.concentricsky.android.khanacademy.util.OfflineVideoManager.java
/** * Cancel ongoing and enqueued video downloads. *//* w w w . j a v a 2s .c o m*/ public void cancelAllVideoDownloads() { final DownloadManager dlm = getDownloadManager(); final DownloadManager.Query q = new DownloadManager.Query(); q.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); // Cancel all tasks - we don't want any more downloads enqueued, and we are // beginning a cancel task so we don't need any previous one. queueExecutor.shutdownNow(); queueExecutor = Executors.newSingleThreadExecutor(); new AsyncTask<Void, Void, Integer>() { @Override protected void onPreExecute() { doToast("Stopping downloads..."); } @Override protected Integer doInBackground(Void... arg) { int result = 0; if (isCancelled()) return result; Cursor c = dlm.query(q); Long[] removed = new Long[c.getCount()]; int i = 0; while (c.moveToNext()) { if (isCancelled()) break; long id = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)); removed[i++] = id; dlm.remove(id); result++; } c.close(); UpdateBuilder<Video, String> u = videoDao.updateBuilder(); try { u.where().in("dlm_id", (Object[]) removed); u.updateColumnValue("download_status", Video.DL_STATUS_NOT_STARTED); u.update(); } catch (SQLException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(Integer result) { if (result > 0) { doToast(result + " downloads cancelled."); } else { doToast("No downloads in queue."); } doOfflineVideoSetChanged(); } @Override protected void onCancelled(Integer result) { if (result > 0) { doToast(result + " downloads cancelled."); } doOfflineVideoSetChanged(); } }.executeOnExecutor(queueExecutor); }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
@SuppressLint("InlinedApi") private File getDownloadedFile(final Long downloadId) throws DownloadNotCompletedException { final DownloadManager dwnlMgr = getDownloadManager(); final Cursor cursor = dwnlMgr.query(new Query().setFilterById(downloadId)); try {// ww w. j a v a 2 s . c om if (!cursor.moveToFirst()) { L.w("Download with id " + downloadId + " not found!"); return null; } final int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); switch (status) { case DownloadManager.STATUS_SUCCESSFUL: final String filePath = cursor .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); return new File(filePath); case DownloadManager.STATUS_FAILED: return null; default: // Not completed L.w("Unexpected DownloadManager.STATUS: " + status); throw new BrandingMgr.DownloadNotCompletedException(); } } finally { cursor.close(); } }