List of usage examples for android.content Context DOWNLOAD_SERVICE
String DOWNLOAD_SERVICE
To view the source code for android.content Context DOWNLOAD_SERVICE.
Click Source Link
From source file:org.cgnet.swara.fragment.EntryFragment.java
@Override public void onClickEnclosure() { getActivity().runOnUiThread(new Runnable() { //TODO/*from w w w . j a va 2 s . co m*/ @Override public void run() { final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos); final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR); final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3); final Uri uri = Uri.parse(enclosure.substring(0, position1)); final String filename = uri.getLastPathSegment(); t.send(new HitBuilders.EventBuilder().setCategory("Button to download audio file was clicked on") .setAction(filename).build()); new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure) // .setMessage(getString(R.string.file) + ": " + filename) .setNegativeButton(R.string.cancel_phone, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // showEnclosure(uri, enclosure, position1, position2); t.send(new HitBuilders.EventBuilder() .setCategory("Button to download audio file was clicked on") .setAction(filename).setValue(0).build()); } }).setPositiveButton(R.string.download_and_save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { t.send(new HitBuilders.EventBuilder() .setCategory("Button to download audio file was clicked on") .setAction(filename).setValue(1).build()); DownloadManager.Request r = new DownloadManager.Request(uri); r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); r.allowScanningByMediaScanner(); r.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); r.setVisibleInDownloadsUi(true); String name = new File(uri.toString()).getName(); String path = Environment.getExternalStorageDirectory().getAbsolutePath(); path += "/CGNet_Swara"; File dir = new File(path); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } r.setDestinationInExternalPublicDir("CGNet_Swara", name); DownloadManager dm = (DownloadManager) MainApplication.getContext() .getSystemService(Context.DOWNLOAD_SERVICE); dm.enqueue(r); Cursor c = mEntryPagerAdapter.getCursor(mCurrentPagerPos); refreshUI(c); // TODO } catch (Exception e) { Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show(); } } }).show(); } }); }
From source file:com.concentricsky.android.khanacademy.app.ManageDownloadsActivity.java
private DownloadManager getDownloadManager() { return (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); }
From source file:com.concentricsky.android.khanacademy.util.OfflineVideoManager.java
private DownloadManager getDownloadManager() { return (DownloadManager) dataService.getSystemService(Context.DOWNLOAD_SERVICE); }
From source file:com.tct.emailcommon.utility.AttachmentUtilities.java
public static void saveAttachmentToExternal(Context context, Attachment attachment, String path) { final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId); final ContentValues cv = new ContentValues(); final long attachmentId = attachment.mId; final long accountId = attachment.mAccountKey; //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S String contentUri = null;/*from ww w .ja v a 2 s.c om*/ //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S final long size; InputStream in = null; OutputStream out = null; try { ContentResolver resolver = context.getContentResolver(); if (Utility.isExternalStorageMounted()) { if (TextUtils.isEmpty(attachment.mFileName)) { // TODO: This will prevent a crash but does not surface the underlying problem // to the user correctly. LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId); throw new IOException("Can't save an attachment with no name"); } // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_S try { String cachedFileUri = attachment.getCachedFileUri(); if (TextUtils.isEmpty(cachedFileUri)) { throw new IOException(); } in = resolver.openInputStream(Uri.parse(cachedFileUri)); } catch (IOException e) { String contentUriForOpen = attachment.getContentUri(); if (TextUtils.isEmpty(contentUriForOpen)) { throw new IOException(); } in = resolver.openInputStream(Uri.parse(contentUriForOpen)); //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_S } catch (IllegalArgumentException e) { String contentUriForOpen = attachment.getContentUri(); if (TextUtils.isEmpty(contentUriForOpen)) { throw new IOException(); } in = resolver.openInputStream(Uri.parse(contentUriForOpen)); } //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_E //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_S //Note: we support save attachment at user designated location. File downloads; if (path != null) { downloads = new File(path); } else { downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); } //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_E downloads.mkdirs(); File file = Utility.createUniqueFile(downloads, attachment.mFileName); out = new FileOutputStream(file); size = copyFile(in, out); String absolutePath = file.getAbsolutePath(); // Although the download manager can scan media files, scanning only happens // after the user clicks on the item in the Downloads app. So, we run the // attachment through the media scanner ourselves so it gets added to // gallery / music immediately. MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null); final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream" : attachment.mMimeType; try { DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S //Note: should use media scanner, it will allow update the //media provider uri column in download manager's database. long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName, true /* use media scanner */, mimeType, absolutePath, size, true /* show notification */); //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E contentUri = dm.getUriForDownloadedFile(id).toString(); } catch (final IllegalArgumentException e) { LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment"); throw new IOException(e); } } else { LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?"); throw new IOException(); } // Update the attachment cv.put(AttachmentColumns.SIZE, size); cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED); // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_S //Note:we have saved the attachment to sd card,so should update the attachment destination external cv.put(AttachmentColumns.UI_DESTINATION, UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_EXTERNAL); // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_E } catch (IOException e) { // Handle failures here... LogUtils.e(Logging.LOG_TAG, "IOException while save an attachment to external storage"); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { LogUtils.e(Logging.LOG_TAG, "ioexception while close the stream"); } } // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_E //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_S // context.getContentResolver().update(uri, cv, null, null); if (cv.size() > 0) { context.getContentResolver().update(uri, cv, null, null); } //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_E //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) { Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey); if (body != null && body.mHtmlContent != null) { cv.clear(); String html = body.mHtmlContent; String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\""; String srcContentUri = " src=\"" + contentUri + "\""; //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S try { html = html.replaceAll(contentIdRe, srcContentUri); } catch (PatternSyntaxException e) { LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern"); } //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E cv.put(BodyColumns.HTML_CONTENT, html); Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv); Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey); } } //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E }
From source file:cn.suishen.email.activity.MessageViewFragmentBase.java
private File performAttachmentSave(MessageViewAttachmentInfo info) { Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.mId); Uri attachmentUri = AttachmentUtilities.getAttachmentUri(mAccountId, attachment.mId); try {/* w ww . ja v a2s. co m*/ File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = Utility.createUniqueFile(downloads, attachment.mFileName); Uri contentUri = AttachmentUtilities.resolveAttachmentIdToContentUri(mContext.getContentResolver(), attachmentUri); InputStream in = mContext.getContentResolver().openInputStream(contentUri); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); String absolutePath = file.getAbsolutePath(); // Although the download manager can scan media files, scanning only happens after the // user clicks on the item in the Downloads app. So, we run the attachment through // the media scanner ourselves so it gets added to gallery / music immediately. MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null); DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE); dm.addCompletedDownload(info.mName, info.mName, false /* do not use media scanner */, info.mContentType, absolutePath, info.mSize, true /* show notification */); // Cache the stored file information. info.setSavedPath(absolutePath); // Update our buttons. updateAttachmentButtons(info); return file; } catch (IOException ioe) { // Ignore. Callers will handle it from the return code. } return null; }
From source file:org.wso2.iot.agent.api.ApplicationManager.java
/** * Initiate downloading via DownloadManager API. * * @param url - File URL.// ww w . j a v a 2 s . c o m * @param appName - Name of the application to be downloaded. */ private void downloadViaDownloadManager(String url, String appName) { final DownloadManager downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(downloadUri); // Restrict the types of networks over which this download may // proceed. request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); // Set whether this download may proceed over a roaming connection. request.setAllowedOverRoaming(true); // Set the title of this download, to be displayed in notifications // (if enabled). request.setTitle(resources.getString(R.string.downloader_message_title)); request.setVisibleInDownloadsUi(false); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); // Set the local destination for the downloaded file to a path // within the application's external files directory request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName); // Enqueue a new download and same the referenceId downloadReference = downloadManager.enqueue(request); new Thread(new Runnable() { @Override public void run() { boolean downloading = true; int progress = 0; while (downloading) { downloadOngoing = true; DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadReference); Cursor cursor = downloadManager.query(query); cursor.moveToFirst(); int bytesDownloaded = cursor .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); if (cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) { downloading = false; } if (cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) { downloading = false; Preference.putString(context, context.getResources().getString(R.string.app_install_status), context.getResources().getString(R.string.app_status_value_download_failed)); Preference.putString(context, context.getResources().getString(R.string.app_install_failed_message), "App download failed due to a connection issue."); } int downloadProgress = 0; if (bytesTotal > 0) { downloadProgress = (int) ((bytesDownloaded * 100l) / bytesTotal); } if (downloadProgress != DOWNLOAD_PERCENTAGE_TOTAL) { progress += DOWNLOADER_INCREMENT; } else { progress = DOWNLOAD_PERCENTAGE_TOTAL; Preference.putString(context, context.getResources().getString(R.string.app_install_status), context.getResources().getString(R.string.app_status_value_download_completed)); } Preference.putString(context, resources.getString(R.string.app_download_progress), String.valueOf(progress)); cursor.close(); } downloadOngoing = false; } }).start(); }
From source file:com.microsoft.onedrive.apiexplorer.ItemFragment.java
/** * Downloads this item// w w w . ja va 2s .co m * @param item The item to download */ private void download(final Item item) { final Activity activity = getActivity(); final DownloadManager downloadManager = (DownloadManager) activity .getSystemService(Context.DOWNLOAD_SERVICE); final String downloadUrl = item.getRawObject().get("@content.downloadUrl").getAsString(); final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl)); request.setTitle(item.name); request.setDescription(activity.getString(R.string.file_from_onedrive)); request.allowScanningByMediaScanner(); if (item.file != null) { request.setMimeType(item.file.mimeType); } request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); downloadManager.enqueue(request); Toast.makeText(activity, activity.getString(R.string.starting_download_message), Toast.LENGTH_LONG).show(); }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static void Download(Context context, RadioSong song, RadioEpisode episode) { String downloadURL = ""; String title = ""; String description = "radio reddit"; String songTitle = context.getString(R.string.app_name); String songArtist = ""; String filename = ""; if (song != null && song.Download_url != null) { if (song.Title != null) songTitle = song.Title;//from w ww . j a va2 s.c o m if (song.Artist != null && song.Redditor != null) songArtist = song.Artist + " (" + song.Redditor + ")"; downloadURL = song.Download_url; } else if (episode != null && episode.Download_url != null) { if (episode.EpisodeTitle != null) songTitle = episode.EpisodeTitle; if (episode.ShowTitle != null) songArtist = episode.ShowTitle; downloadURL = episode.Download_url; } title = songTitle + " by " + songArtist; filename = songArtist + " " + songTitle + ".mp3"; filename = filename.replace(" ", "_"); if (!downloadURL.equals("")) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(downloadURL); File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); path = new File(path, "radioreddit"); path.mkdirs(); DownloadManager.Request request = new DownloadManager.Request(uri); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setTitle(title).setDescription(description).setMimeType("audio/mpeg") .setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "/radioreddit/" + filename); long lastDownload = -1L; lastDownload = downloadManager.enqueue(request); } }
From source file:me.piebridge.bible.Bible.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) public DownloadInfo download(String filename) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { return null; }//ww w . ja va2s .com if (getExternalFilesDirWrapper() == null) { return null; } String url = BIBLEDATA_PREFIX + filename; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setTitle(filename); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); return DownloadInfo.getDownloadInfo(mContext, dm.enqueue(request)); }
From source file:im.delight.android.webview.AdvancedWebView.java
/** * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage * <p/>/* w ww.j a v a2 s. c o m*/ * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE` * <p/> * Only supported on API level 9 (Android 2.3) and above * * @param context a valid `Context` reference * @param fromUrl the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)` * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg` * @return whether the download has been successfully handled or not */ @SuppressLint("NewApi") public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) { if (Build.VERSION.SDK_INT < 9) { throw new RuntimeException("Method requires API level 9 or above"); } final Request request = new Request(Uri.parse(fromUrl)); if (Build.VERSION.SDK_INT >= 11) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename); final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); try { try { dm.enqueue(request); } catch (SecurityException e) { if (Build.VERSION.SDK_INT >= 11) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); } dm.enqueue(request); } return true; } // if the download manager app has been disabled on the device catch (IllegalArgumentException e) { // show the settings screen where the user can enable the download manager app again openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER); return false; } }