List of usage examples for android.os Environment getExternalStoragePublicDirectory
public static File getExternalStoragePublicDirectory(String type)
From source file:com.jwetherell.quick_response_code.EncoderActivity.java
public Uri getLocalBitmapUri(ImageView imageView) { // Extract Bitmap from ImageView drawable Drawable drawable = imageView.getDrawable(); Bitmap bmp = null;// w ww . ja v a 2 s.c o m if (drawable instanceof BitmapDrawable) { bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); } else { return null; } // Store image to default external storage directory Uri bmpUri = null; try { File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "miwifiQR_" + System.currentTimeMillis() + ".png"); file.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); out.close(); bmpUri = Uri.fromFile(file); } catch (IOException e) { e.printStackTrace(); } return bmpUri; }
From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java
/** * Get the directory where captured images are stored. * * @return The media storage directory//from w ww.j a v a 2 s . c o m */ @NonNull private static File getMediaStorageDir() throws IOException { final File mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); final File albumDir = new File(mediaStorageDir, ALBUM_DIR); if (!albumDir.exists()) { if (!albumDir.mkdirs()) { throw new IOException("Failure creating directories"); } } return albumDir; }
From source file:locationkitapp.locationkit.locationkitapp.MapsActivity.java
private void emailVisitHistory() { ArrayList<Uri> uris = new ArrayList<Uri>(); String filename = String.format(Locale.ENGLISH, "data_%d.csv", System.currentTimeMillis()); File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File file = new File(root, filename); if (!file.exists()) { try {/*from ww w. j a v a2 s . c o m*/ file.createNewFile(); } catch (IOException e) { Log.e(LOG_TAG, "file failed", e); return; } } try { FileOutputStream os = new FileOutputStream(file); os.write( "arrival_date,detected_time,visit_id,departure_date,category,subcategory,venue_name,street,city,state,zip,detection_method,latitude,longitude,from_place\n" .getBytes()); for (Visit v : mVisits) { os.write(visitRow(v).getBytes()); } os.close(); } catch (IOException e) { Log.e(LOG_TAG, "ioexception on file", e); return; } uris.add(LKDataManager.EXPORT_DB(this)); Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); emailIntent.setType("text/plain"); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "LocationKitApp "); emailIntent.putExtra(Intent.EXTRA_TEXT, "Visits Recorded by LocationKitApp"); uris.add(Uri.fromFile(file)); emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); startActivity(Intent.createChooser(emailIntent, "Pick an Email provider")); }
From source file:com.lastsoft.plog.adapter.PlayAdapter.java
@Override public void onBindViewHolder(final ViewHolder viewHolder, final int position) { //Log.d(TAG, "Element " + position + " set."); // Get element from your dataset at this position and replace the contents of the view // with that element //if (searchQuery.equals("") || (games.get(position).gameName.toLowerCase().contains(searchQuery.toLowerCase()))) { DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy"); Date theDate = plays.get(position).playDate; long diff = new Date().getTime() - theDate.getTime(); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); String output_date;//from w w w . j ava2s .c om if (days == 0) { output_date = mActivity.getString(R.string.played_label) + mActivity.getString(R.string.less_than_a_day_ago); } else if (days == 1) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.day_ago_label); } else if (days <= 6) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.days_ago_label); } else { output_date = mActivity.getString(R.string.played_label) + outputFormatter.format(theDate); // Output : 01/20/2012 } //String output_date = outputFormatter.format(theDate); // Output : 01/20/2012 if (plays.get(position).playLocation != null) { output_date = output_date + " at " + Location.findById(Location.class, plays.get(position).playLocation.getId()).locationName; } if (plays.get(position).playNotes != null && !plays.get(position).playNotes.equals("")) { viewHolder.getPlayDescView().setVisibility(View.VISIBLE); viewHolder.getPlayDescView().setText("\"" + plays.get(position).playNotes + "\""); } else { Log.d("V1", "gone"); viewHolder.getPlayDescView().setVisibility(View.GONE); } viewHolder.getGameNameView().setText(GamesPerPlay.getBaseGame(plays.get(position)).gameName); viewHolder.getPlayDateView().setText(output_date); viewHolder.getImageView().setTransitionName("imageTrans" + position); viewHolder.getImageView().setTag("imageTrans" + position); viewHolder.getGameNameView().setTransitionName("nameTrans" + position); viewHolder.getGameNameView().setTag("nameTrans" + position); viewHolder.getPlayDateView().setTransitionName("dateTrans" + position); viewHolder.getPlayDateView().setTag("dateTrans" + position); viewHolder.getClickLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) { return; } mLastClickTime = SystemClock.elapsedRealtime(); ((MainActivity) mActivity).onPlayClicked(plays.get(position), mFragment, viewHolder.getImageView(), viewHolder.getGameNameView(), viewHolder.getPlayDateView(), position, fromDrawer, playListType, sortType, searchQuery); } }); viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playPopup(view, position); } }); String playPhoto; playPhoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Plog/" + plays.get(position).playPhoto; if (plays.get(position).playPhoto != null && (plays.get(position).playPhoto.equals("") || new File(playPhoto).exists() == false)) { String gameThumb = GamesPerPlay.getBaseGame(plays.get(position)).gameThumb; if (gameThumb != null && !gameThumb.equals("")) { //ImageLoader.getInstance().displayImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, options, null); Picasso.with(mActivity).load("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb) .fit().into(viewHolder.getImageView()); } else { viewHolder.getImageView().setImageDrawable(null); } } else { String thumbPath = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; if (new File(thumbPath).exists()) { //ImageLoader.getInstance().displayImage("file://" + thumbPath, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("file://" + playPhoto, options, null); Picasso.with(mActivity).load("file://" + thumbPath).into(viewHolder.getImageView()); } else { ImageLoader.getInstance().displayImage("file://" + playPhoto, viewHolder.getImageView(), options); //Picasso.with(mActivity).load(playPhoto).fit().into(viewHolder.getImageView()); // make a thumb String thumbPath2 = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; try { FileInputStream fis; fis = new FileInputStream(playPhoto); Bitmap imageBitmap = BitmapFactory.decodeStream(fis); Bitmap b = resizeImageForImageView(imageBitmap, 500); if (b != null) { try { b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(thumbPath2))); } catch (Exception ignored) { } b = null; } if (imageBitmap != null) { imageBitmap = null; } Picasso.with(mActivity).load("file://" + thumbPath2).resize(500, 500).centerCrop() .into(viewHolder.getImageView()); } catch (Exception e) { e.printStackTrace(); } //still use the og picture. next time there will be a thumb } //Picasso.with(mActivity).load(playPhoto).fetch(); //ImageLoader.getInstance().loadImage(playPhoto, options, null); } viewHolder.getPlayWinnerView().setTypeface(null, Typeface.ITALIC); /*if (plays.get(position).winners != null) { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + plays.get(position).winners); }else{*/ String winners = Play.getWinners(plays.get(position)); if (winners == null) { viewHolder.getPlayWinnerView() .setText(mActivity.getString(R.string.winners) + mActivity.getString(R.string.none)); } else { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + winners); } //} }
From source file:net.nanocosmos.bintu.demo.encoder.activities.StreamActivity.java
private nanoStreamSettings configureNanostreamSettings() { if (recordMp4) { try {// w ww .ja v a 2s .co m // get the external DCIM Folder for mp4 recording. // for a docu about mp4 recording see http://www.nanocosmos.de/v4/documentation/android_mp4_recording File _path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File subDir = new File(_path, "BintuStreamer"); boolean result = true; if (!subDir.exists()) { result = subDir.mkdirs(); } if (result) { File filePath = new File(subDir, "Test.mp4"); int i = 1; while (filePath.exists()) { filePath = new File(subDir, "Test_" + i + ".mp4"); i++; } mp4FilePath = filePath.getAbsolutePath(); } else { recordMp4 = false; } } catch (Exception e) { recordMp4 = false; Logging.log(Logging.LogLevel.ERROR, TAG, "Failed to get video path. ", e); } } // new AdaptiveBitrateControlSettings(mode) creates a default AdaptiveBitrateControlSettings object // with the following values: // adaptive bitrate control mode = mode (DISABLE, QUALITY_DEGRADE, FRAME_DROP, QUALITY_DEGRADE_AND_FRAME_DROP) // min bit rate = 50k // max bit rate = 2M // flush Buffer Threshold = 50% // min frame rate = 5 abcSettings = new AdaptiveBitrateControlSettings(abcMode); abcSettings.SetMaximumBitrate((int) (videoBitrate * 1.5)); // new LogSettings() creates a default LogSettings object with the following values: // log path = own directory (e.g. /sdcard/Android/com.example.appname/files/) // log name = RTMPStream.log // Log level = LogLevel.ERROR // log enabled = 1 String dir = new String("logs"); File f = new File(getExternalFilesDir(dir), ""); String path = f.getAbsolutePath(); logSettings = new Logging.LogSettings(path, "nanoStreamRTMP.log", Logging.LogLevel.VERBOSE, 1); // new VideoSettings() creates a default VideoSettings object with the following values: // video resolution = 640x480 // video bit rate = 500k // video frame rate = 15 // key frame interval = 5 // video source type = VideoSourceType.INTERNAL_BACK // use auto focus = true // use torch = false // aspect ratio = AspectRatio.RATIO_KEEP_INPUT VideoSettings vs = new VideoSettings(); vs.setBitrate(videoBitrate); vs.setFrameRate(videoFramerate); vs.setResolution(videoResolution); vs.setVideoSourceType(videoSourceType); vs.setAspectRatio(videoAspectRatio); vs.setKeyFrameInterval(videoKeyFrameInterval); vs.setUseAutoFocus(useAutoFocus); vs.setUseTorch(useTorch); // new AudioSettings() creates a default AudioSettings object with the following values: // audio channels = 2 // audio bit rate = 64k // audio sample rate = 44.1k AudioSettings as = new AudioSettings(); as.setBitrate(audioBitrate); as.setChannels(audioChannels); as.setSamplerate(audioSamplerate); // new nanoStreamSettings() creates a default nanoStreamSettings object with the following values: // has video = true // video settings = default video settings // has audio = true // audio settings = default audio settings // preview holder = null // license = "" // stream url = "" // stream name = "" // event listener = null // Adaptive Bit rate settings = disabled // log settings = default log settings // send rtmp = true // record MP4 = false // mp4 path = "" // you need to set at least the license, stream url and the stream name to be able to start a stream. nanoStreamSettings nss = new nanoStreamSettings(); nss.setVideoSettings(vs); nss.setHaveVideo(streamVideo); nss.setPreviewSurface(surface); nss.setAudioSettings(as); nss.setHaveAudio(streamAudio); nss.setAbcSettings(abcSettings); nss.setLogSettings(logSettings); nss.setLicense(Configuration.NANOSTREAM_LICENSE); nss.setStreamUrl(serverUrl); nss.setStreamName(streamName); nss.setAuthUser(authUser); nss.setAuthPassword(authPassword); nss.setSendRtmp(sendRtmp); nss.setEventListener(this); nss.setMp4Path(mp4FilePath); nss.setRecordMp4(recordMp4); return nss; }
From source file:com.example.user.lstapp.CreatePlaceFragment.java
/** * Used to return the camera File output. * @return/* w ww .j ava2s. com*/ */ private File getOutputMediaFile() { File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "UltimateCameraGuideApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("Camera Guide", "Required media storage does not exist"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); //DialogHelper.showDialog( "Success!","Your picture has been saved!",getActivity()); return mediaFile; }
From source file:org.chromium.latency.walt.MainActivity.java
public String saveLogToFile() { // Save to file to later fire an Intent.ACTION_SEND // This allows to either send the file as email attachment // or upload it to Drive. // The permissions for attachments are a mess, writing world readable files // is frowned upon, but deliberately giving permissions as part of the intent is // way too cumbersome. String fname = "qstep_log.txt"; // A reasonable world readable location,on many phones it's /storage/emulated/Documents // TODO: make this location configurable? File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); File file = null;//www . j a v a2 s . com FileOutputStream outStream = null; Date now = new Date(); logger.log("Saving log to:\n" + path.getPath() + "/" + fname); logger.log("On: " + now.toString()); try { if (!path.exists()) { path.mkdirs(); } file = new File(path, fname); outStream = new FileOutputStream(file); outStream.write(logger.getLogText().getBytes()); outStream.close(); logger.log("Log saved"); } catch (Exception e) { e.printStackTrace(); logger.log("Exception:\n" + e.getMessage()); } return file.getPath(); }
From source file:org.awesomeapp.messenger.ui.ConversationDetailActivity.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)) { // 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(mConvoView.getHistoryView(), R.string.grant_perms, Snackbar.LENGTH_LONG).show(); } else {/*from ww w .j a va2s .c o 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:com.dycode.jepretstory.mediachooser.activity.HomeFragmentActivity.java
/** Create a File for saving an image or video */ private static File getOutputMediaFile(MediaType type) { File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), MediaChooserConstants.folderName); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; }//from w ww . j a v a 2 s.c o m } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile; if (type == MediaType.IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MediaType.VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; }
From source file:com.uberspot.storageutils.StorageUtils.java
public File getPictureDirectory(String albumName) { return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName); }