List of usage examples for android.os Environment DIRECTORY_DOWNLOADS
String DIRECTORY_DOWNLOADS
To view the source code for android.os Environment DIRECTORY_DOWNLOADS.
Click Source Link
From source file:com.example.android.camera2basic.Camera2VideoFragment.java
/** Create a File for saving an image or video */ private static File getOutputMediaFile(int type) { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCameraApp"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; }/*ww w . j a va2 s . c o m*/ } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpeg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; }
From source file:org.cgnet.swara.fragment.EntryFragment.java
@Override public void onClickEnclosure() { getActivity().runOnUiThread(new Runnable() { //TODO//from ww w . j a va2 s . c o 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:fr.kwiatkowski.apktrack.service.WebService.java
/** * Downloads the APK for a given app if a download URL is available. * APK downloads take place through the Download Service. Files are stored on a dedicated * folder on the external storage of the device. * @param app The app whose APK is to be downloaded. */// www . j a v a 2s. c om private void _download_apk(InstalledApp app, String request_source) { if (app.get_download_url() == null) { return; } Uri uri = Uri .parse(String.format(app.get_download_url(), app.get_display_name(), app.get_latest_version())); DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(uri); // Indicate whether the download may take place over mobile data. // Download over data is okay on user click, but respect the preference for background checks. if (ScheduledCheckService.SERVICE_SOURCE.equals(request_source) && PreferenceManager .getDefaultSharedPreferences(this).getBoolean(SettingsFragment.KEY_PREF_WIFI_ONLY, true)) { request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); } else { request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); } // Don't download APKs when roaming. request.setAllowedOverRoaming(false).setTitle(getString(getApplicationInfo().labelRes)) .setDescription(app.get_display_name() + " " + app.get_latest_version() + ".apk") .setVisibleInDownloadsUi(false).setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, app.get_package_name() + "-" + app.get_latest_version() + ".apk"); long id = dm.enqueue(request); app.set_download_id(id); app.save(); EventBusHelper.post_sticky(ModelModifiedMessage.event_type.APP_UPDATED, app.get_package_name()); }
From source file:com.concentricsky.android.khanacademy.util.OfflineVideoManager.java
private File getDownloadDir() { File file = dataService.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); return file; }
From source file:com.mobileobservinglog.support.HtmlExporter.java
private File getDefaultDirectory() { String state = Environment.getExternalStorageState(); //If the external card is not available, then establish a file location on the internal file system if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); } else {/*from w w w .j av a 2s. c om*/ return Environment.getDownloadCacheDirectory(); } }
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;// ww w .jav a2s . 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:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java
private void runScheduledAlarm(int initialDelay, int period) { proximityAlertWatcher = new FiskinfoScheduledTaskExecutor(2).scheduleAtFixedRate(new Runnable() { @Override/*from w w w . j ava 2 s. co m*/ public void run() { // Need to get alarm status and handle kill if (!cacheDeserialized) { String directoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); String directoryName = "FiskInfo"; String filename = "collisionCheckToolsFile"; String format = "OLEX"; String filePath = directoryPath + "/" + directoryName + "/" + filename + "." + format; tools = fiskInfoUtility.deserializeFiskInfoPolygon2D(filePath); cacheDeserialized = true; // DEMO: add point here for testing/demo purposes // Point point = new Point(69.650543, 18.956831); // tools.addPoint(point); } else { if (alarmFiring) { return; } double latitude, longitude; if (mGpsLocationTracker.canGetLocation()) { latitude = mGpsLocationTracker.getLatitude(); cachedLat = latitude; longitude = mGpsLocationTracker.getLongitude(); cachedLon = longitude; Log.i("GPS-LocationTracker", String.format("latitude: %s, ", latitude)); Log.i("GPS-LocationTracker", String.format("longitude: %s", longitude)); } else { mGpsLocationTracker.showSettingsAlert(); return; } Point userPosition = new Point(cachedLat, cachedLon); if (tools.checkCollisionWithPoint(userPosition, cachedDistance)) { alarmFiring = true; Looper.prepare(); notifyUserOfProximityAlert(); } } System.out.println("Collision check run"); } }, initialDelay, period, TimeUnit.SECONDS); }
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 {/*ww w . ja va2 s . 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:me.piebridge.bible.Bible.java
@SuppressLint("NewApi") private void checkBibleData(boolean all) { synchronized (versionsCheckingLock) { if ((!checking || !all) && versions.size() > 0) { Log.d(TAG, "cancel checking"); return; }//from w ww . j a v a 2s . c om if (!all) { if (checkVersionsSync(false) > 0) { return; } } checkApkData(); checkZipData(Environment.getExternalStorageDirectory()); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { checkZipData(new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS)); } else { checkZipData(new File(Environment.getExternalStorageDirectory(), "Download")); } checkVersionsSync(true); } }
From source file:org.wso2.iot.agent.api.ApplicationManager.java
/** * Initiate downloading via DownloadManager API. * * @param url - File URL.// w ww .java 2s. c om * @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(); }