List of usage examples for android.os Environment getExternalStoragePublicDirectory
public static File getExternalStoragePublicDirectory(String type)
From source file:org.glucosio.android.presenter.ExportPresenter.java
private boolean dirExists() { final File file = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/glucosio"); return file.exists() || file.mkdirs(); }
From source file:com.geekandroid.sdk.sample.crop.ResultActivity.java
private void copyFileToDownloads(Uri croppedFileUri) throws Exception { String downloadsDirectoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(), croppedFileUri.getLastPathSegment()); File saveFile = new File(downloadsDirectoryPath, filename); FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath())); FileOutputStream outStream = new FileOutputStream(saveFile); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inStream.close();/*from w ww.ja va 2s . co m*/ outStream.close(); showNotification(saveFile); }
From source file:it.rignanese.leo.slimfacebook.PictureActivity.java
private void DownloadPicture(String url, boolean share) { //check permission if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { //ask permission Toast.makeText(getApplicationContext(), getString(R.string.acceptPermissionAndRetry), Toast.LENGTH_LONG) .show();//from ww w. j a v a 2 s .co m int requestResult = 0; ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, requestResult); } else { //download photo DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setTitle("SlimSocial Download"); // 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 path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(); if (savedPreferences.getBoolean("pref_useSlimSocialSubfolderToDownloadedFiles", false)) { path += "/SlimSocial"; } request.setDestinationInExternalPublicDir(path, "SlimSocial.jpg"); if (share) request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); // get download service and enqueue file long _idDownloadedFile = downloadManager.enqueue(request); if (share) idDownloadedFile = _idDownloadedFile; else Toast.makeText(getApplicationContext(), getString(R.string.downloadingPhoto), Toast.LENGTH_LONG) .show(); } }
From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java
public static File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "MAGE_" + timeStamp; File pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File directory = new File(pictures, "MAGE"); if (!directory.exists()) { directory.mkdirs();/*from w w w . ja v a 2 s . c o m*/ } return File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ directory /* directory */ ); }
From source file:org.quantumbadger.redreader.image.ShareImageCallback.java
@Override public void onPermissionGranted() { final RedditAccount anon = RedditAccountManager.getAnon(); LinkHandler.getImageInfo(activity, uri, Constants.Priority.IMAGE_VIEW, 0, new GetImageInfoListener() { @Override/*from w w w.j av a2 s. c o m*/ public void onFailure(final @CacheRequest.RequestFailureType int type, final Throwable t, final Integer status, final String readableMessage) { final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, uri); General.showResultDialog(activity, error); } @Override public void onSuccess(final ImageInfo info) { CacheManager.getInstance(activity) .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon, null, Constants.Priority.IMAGE_VIEW, 0, DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DOWNLOAD_QUEUE_IMMEDIATE, false, false, activity) { @Override protected void onCallbackException(Throwable t) { BugReportActivity.handleGlobalError(context, t); } @Override protected void onDownloadNecessary() { General.quickToast(context, R.string.download_downloading); } @Override protected void onDownloadStarted() { } @Override protected void onFailure(@CacheRequest.RequestFailureType int type, Throwable t, Integer status, String readableMessage) { final RRError error = General.getGeneralErrorForFailure(context, type, t, status, url.toString()); General.showResultDialog(activity, error); } @Override protected void onProgress(boolean authorizationInProgress, long bytesRead, long totalBytes) { } @Override protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp, UUID session, boolean fromCache, String mimetype) { String filename = General.filenameFromString(info.urlOriginal); File dst = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), filename); if (dst.exists()) { int count = 0; while (dst.exists()) { count++; dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), count + "_" + filename.substring(1)); } } Uri sharedImage = FileProvider.getUriForFile(context, "org.quantumbadger.redreader.provider", dst); try { final InputStream cacheFileInputStream = cacheFile.getInputStream(); if (cacheFileInputStream == null) { notifyFailure(CacheRequest.REQUEST_FAILURE_CACHE_MISS, null, null, "Could not find cached image"); return; } General.copyFile(cacheFileInputStream, dst); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, sharedImage); shareIntent.setType(mimetype); activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.action_share_image))); } catch (IOException e) { notifyFailure(CacheRequest.REQUEST_FAILURE_STORAGE, e, null, "Could not copy file"); return; } activity.sendBroadcast( new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, sharedImage)); General.quickToast(context, context.getString(R.string.action_save_image_success) + " " + dst.getAbsolutePath()); } }); } @Override public void onNotAnImage() { General.quickToast(activity, R.string.selected_link_is_not_image); } }); }
From source file:com.royclarkson.springagram.PhotoAddFragment.java
private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File image = File.createTempFile(imageFileName, ".jpg", storageDir); this.photoPath = image.getAbsolutePath(); if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "PhotoPath: " + this.photoPath); }/*from ww w . j a va 2s. com*/ return image; }
From source file:de.baumann.browser.popups.Popup_files.java
private void setFilesList() { deleteDatabase("files_DB_v01.db"); File f = new File(sharedPref.getString("files_startFolder", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath())); final File[] files = f.listFiles(); Arrays.sort(files, new Comparator<File>() { @Override// w ww .j a v a2s.c o m public int compare(File file1, File file2) { if (file1.isDirectory()) { if (file2.isDirectory()) { return String.valueOf(file1.getName().toLowerCase()) .compareTo(file2.getName().toLowerCase()); } else { return -1; } } else { if (file2.isDirectory()) { return 1; } else { return String.valueOf(file1.getName().toLowerCase()) .compareTo(file2.getName().toLowerCase()); } } } }); // looping through all items <item> if (files.length == 0) { Snackbar.make(listView, R.string.toast_files, Snackbar.LENGTH_LONG).show(); } for (File file : files) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String file_Name = file.getName().substring(0, 1).toUpperCase() + file.getName().substring(1); String file_Size = getReadableFileSize(file.length()); String file_date = formatter.format(new Date(file.lastModified())); String file_path = file.getAbsolutePath(); String file_ext; if (file.isDirectory()) { file_ext = "."; } else { file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")); } db.open(); if (db.isExist(file_Name)) { Log.i(TAG, "Entry exists" + file_Name); } else { db.insert(file_Name, file_Size, file_ext, file_path, file_date); } } try { db.insert("...", "", "", "", ""); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } //display data final int layoutstyle = R.layout.list_item; int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes }; String[] column = new String[] { "files_title", "files_content", "files_creation" }; final Cursor row = db.fetchAllData(this); adapter = new SimpleCursorAdapter(this, layoutstyle, row, column, xml_id, 0) { @Override public View getView(final int position, View convertView, ViewGroup parent) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final File pathFile = new File(files_attachment); View v = super.getView(position, convertView, parent); final ImageView iv = (ImageView) v.findViewById(R.id.icon_notes); iv.setVisibility(View.VISIBLE); if (pathFile.isDirectory()) { iv.setImageResource(R.drawable.folder); } else { switch (files_icon) { case "": iv.setImageResource(R.drawable.arrow_up_dark); break; case ".m3u8": case ".mp3": case ".wma": case ".midi": case ".wav": case ".aac": case ".aif": case ".amp3": case ".weba": case ".ogg": iv.setImageResource(R.drawable.file_music); break; case ".mpeg": case ".mp4": case ".webm": case ".qt": case ".3gp": case ".3g2": case ".avi": case ".f4v": case ".flv": case ".h261": case ".h263": case ".h264": case ".asf": case ".wmv": try { Glide.with(Popup_files.this).load(files_attachment) // or URI/path .override(76, 76).centerCrop().into(iv); //imageView to set thumbnail to } catch (Exception e) { Log.w("HHS_Moodle", "Error load thumbnail", e); iv.setImageResource(R.drawable.file_video); } break; case ".vcs": case ".vcf": case ".css": case ".ics": case ".conf": case ".config": case ".java": case ".html": iv.setImageResource(R.drawable.file_xml); break; case ".apk": iv.setImageResource(R.drawable.android); break; case ".pdf": iv.setImageResource(R.drawable.file_pdf); break; case ".rtf": case ".csv": case ".txt": case ".doc": case ".xls": case ".ppt": case ".docx": case ".pptx": case ".xlsx": case ".odt": case ".ods": case ".odp": iv.setImageResource(R.drawable.file_document); break; case ".zip": case ".rar": iv.setImageResource(R.drawable.zip_box); break; case ".gif": case ".bmp": case ".tiff": case ".svg": case ".png": case ".jpg": case ".JPG": case ".jpeg": try { Glide.with(Popup_files.this).load(files_attachment) // or URI/path .diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true) .override(76, 76).centerCrop().into(iv); //imageView to set thumbnail to } catch (Exception e) { Log.w("HHS_Moodle", "Error load thumbnail", e); iv.setImageResource(R.drawable.file_image); } break; default: iv.setImageResource(R.drawable.file); break; } } if (files_attachment.isEmpty()) { new Handler().postDelayed(new Runnable() { public void run() { iv.setImageResource(R.drawable.arrow_up_dark); } }, 350); } return v; } }; //display data by filter final String note_search = sharedPref.getString("filter_filesBY", "files_title"); sharedPref.edit().putString("filter_filesBY", "files_title").apply(); editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s.toString()); } }); adapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(CharSequence constraint) { return db.fetchDataByFilter(constraint.toString(), note_search); } }); listView.setAdapter(adapter); //onClick function listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final File pathFile = new File(files_attachment); if (pathFile.isDirectory()) { try { sharedPref.edit().putString("files_startFolder", files_attachment).apply(); setFilesList(); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } } else if (files_attachment.equals("")) { try { final File pathActual = new File(sharedPref.getString("files_startFolder", Environment.getExternalStorageDirectory().getPath())); sharedPref.edit().putString("files_startFolder", pathActual.getParent()).apply(); setFilesList(); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } } else { helper_main.open(files_icon, Popup_files.this, pathFile, listView); } } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final File pathFile = new File(files_attachment); if (pathFile.isDirectory()) { Snackbar snackbar = Snackbar .make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { sharedPref.edit().putString("files_startFolder", pathFile.getParent()).apply(); deleteRecursive(pathFile); setFilesList(); } }); snackbar.show(); } else { final CharSequence[] options = { getString(R.string.choose_menu_2), getString(R.string.choose_menu_3), getString(R.string.choose_menu_4) }; final AlertDialog.Builder dialog = new AlertDialog.Builder(Popup_files.this); dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); dialog.setItems(options, new DialogInterface.OnClickListener() { @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals(getString(R.string.choose_menu_2))) { if (pathFile.exists()) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("image/png"); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, files_title); sharingIntent.putExtra(Intent.EXTRA_TEXT, files_title); Uri bmpUri = Uri.fromFile(pathFile); sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_file)))); } } if (options[item].equals(getString(R.string.choose_menu_4))) { Snackbar snackbar = Snackbar .make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { pathFile.delete(); setFilesList(); } }); snackbar.show(); } if (options[item].equals(getString(R.string.choose_menu_3))) { sharedPref.edit().putString("pathFile", files_attachment).apply(); editText.setVisibility(View.VISIBLE); helper_editText.showKeyboard(Popup_files.this, editText, 2, files_title, getString(R.string.bookmark_edit_title)); } } }); dialog.show(); } return true; } }); }
From source file:org.awesomeapp.messenger.ui.GalleryActivity.java
void startPhotoTaker() { int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (permissionCheck == PackageManager.PERMISSION_DENIED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { View view = findViewById(R.id.gallery_fragment); // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. Snackbar.make(view, R.string.grant_perms, Snackbar.LENGTH_LONG).show(); } else {/*from ww w .ja v a 2 s.co m*/ // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, MY_PERMISSIONS_REQUEST_CAMERA); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } else { // create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "cs_" + new Date().getTime() + ".jpg"); mLastPhoto = Uri.fromFile(photo); intent.putExtra(MediaStore.EXTRA_OUTPUT, mLastPhoto); // start the image capture Intent startActivityForResult(intent, ConversationDetailActivity.REQUEST_TAKE_PICTURE); } }
From source file:ufms.br.com.ufmsapp.task.DownloadTask.java
@Override protected String doInBackground(String... sUrl) { InputStream input = null;/*from w ww .ja v a 2 s. c o m*/ OutputStream output = null; HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } int fileLength = connection.getContentLength(); input = connection.getInputStream(); output = new FileOutputStream(new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { if (isCancelled()) { input.close(); return null; } total += count; if (fileLength > 0) publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; }
From source file:com.sebible.cordova.videosnapshot.VideoSnapshot.java
/** * Take snapshots of a video file//ww w.j a v a 2 s .com * * @param source path of the file * @param count of snapshots that are gonna be taken */ private void snapshot(final JSONObject options) { final CallbackContext context = this.callbackContext; this.cordova.getThreadPool().execute(new Runnable() { public void run() { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { int count = options.optInt("count", 1); int countPerMinute = options.optInt("countPerMinute", 0); int quality = options.optInt("quality", 90); String source = options.optString("source", ""); Boolean timestamp = options.optBoolean("timeStamp", true); String prefix = options.optString("prefix", ""); int textSize = options.optInt("textSize", 48); if (source.isEmpty()) { throw new Exception("No source provided"); } JSONObject obj = new JSONObject(); obj.put("result", false); JSONArray results = new JSONArray(); Log.i("snapshot", "Got source: " + source); Uri p = Uri.parse(source); String filename = p.getLastPathSegment(); FileInputStream in = new FileInputStream(new File(p.getPath())); retriever.setDataSource(in.getFD()); String tmp = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); long duration = Long.parseLong(tmp); if (countPerMinute > 0) { count = (int) (countPerMinute * duration / (60 * 1000)); } if (count < 1) { count = 1; } long delta = duration / (count + 1); // Start at duration * 1 and ends at duration * count if (delta < 1000) { // min 1s delta = 1000; } Log.i("snapshot", "duration:" + duration + " delta:" + delta); File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); for (int i = 1; delta * i < duration && i <= count; i++) { String filename2 = filename.replace('.', '_') + "-snapshot" + i + ".jpg"; File dest = new File(storage, filename2); if (!storage.exists() && !storage.mkdirs()) { throw new Exception("Unable to access storage:" + storage.getPath()); } FileOutputStream out = new FileOutputStream(dest); Bitmap bm = retriever.getFrameAtTime(i * delta * 1000); if (timestamp) { drawTimestamp(bm, prefix, delta * i, textSize); } bm.compress(Bitmap.CompressFormat.JPEG, quality, out); out.flush(); out.close(); results.put(dest.getAbsolutePath()); } obj.put("result", true); obj.put("snapshots", results); context.success(obj); } catch (Exception ex) { ex.printStackTrace(); Log.e("snapshot", "Exception:", ex); fail("Exception: " + ex.toString()); } finally { try { retriever.release(); } catch (RuntimeException ex) { } } } }); }