Java Code Examples for android.os.Environment.getExternalStoragePublicDirectory()

The following are Jave code examples for showing how to use getExternalStoragePublicDirectory() of the android.os.Environment class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AdoBot   File: UpdateActivity.java   View Source Code Vote up 6 votes
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pkg = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), Constants.UPDATE_PKG_FILE_NAME);
    if (!pkg.exists()) {
        Context context = getApplicationContext();
        CharSequence text = "Software is up to date.";
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
        finish();
    }
    setContentView(R.layout.activity_prompt_update);
    btnUpdate = (Button) findViewById(R.id.update_btn);
    btnUpdate.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            doUpdate();
        }
    });
}
 
Example 2
Project: CommonsLab   File: MainActivity.java   View Source Code Vote up 6 votes
public void startRecordingVideo() {
    if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM), "Camera");
        videoFile = new File(storageDir, "Commons_" + timeStamp + ".mp4");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            videoUri = FileProvider.getUriForFile(MainActivity.this,
                    BuildConfig.APPLICATION_ID + ".provider",
                    videoFile);
        } else {
            videoUri = Uri.fromFile(videoFile);
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, VIDEO_CAPTURE);
    } else {
        Toast.makeText(this, R.string.no_camera_on_device, Toast.LENGTH_LONG).show();
    }
}
 
Example 3
Project: shareNote   File: BottomSheetImagePicker.java   View Source Code Vote up 6 votes
/**
 * For images captured from the camera, we need to create a File first to tell the camera
 * where to store the image.
 *
 * @return the File created for the image to be store under.
 */
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    selectedImageUri = Uri.fromFile(imageFile);
    return imageFile;
}
 
Example 4
Project: smart-device-cloud   File: Utilities.java   View Source Code Vote up 6 votes
public static String getFile() {
    File folder = Environment.getExternalStoragePublicDirectory("/");
    if (!folder.exists()) {
        folder.mkdir();
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    //String imageFileName = "image"+ timeStamp + "_";
    String imageFileName = "Temp_Image";
    File image_file = null;

    try {
        image_file = File.createTempFile(imageFileName, ".jpg", folder);
    } catch (IOException e) {
        e.printStackTrace();
    }


    return image_file.getAbsolutePath();
}
 
Example 5
Project: Raffler-Android   File: ChatActivity.java   View Source Code Vote up 6 votes
private void cameraIntent() throws IOException
{
    if (checkPermissions()){

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();
        String file = dir+"photo.jpg";
        File newfile = new File(file);
        try {
            newfile.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        mCurrentPhotoPath = Uri.fromFile(newfile);

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoPath);
        startActivityForResult(takePictureIntent, REQUEST_CAMERA);
    }
}
 
Example 6
Project: GCSApp   File: BitmapCompressUtil.java   View Source Code Vote up 6 votes
private Exception compress(Bitmap bitmap) {
    File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    if (!outDir.exists()) {
        outDir.mkdirs();
    }
    File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
    mFileOutputPath = outFile.getAbsolutePath();
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(outFile);
        bitmap.compress(compressFormat, compressQuality, fileOutputStream);
        bitmap.recycle();
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
        return e;
    }
    return null;
}
 
Example 7
Project: TakingPhotosSimply   File: MainActivity.java   View Source Code Vote up 6 votes
private File createImageFile(boolean privateStorage) throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = privateStorage ? getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}
 
Example 8
Project: JYShare   File: FileToSD.java   View Source Code Vote up 6 votes
public FileToSD(Context context,String inputPath,String outputPath,String versionName) throws IOException
{
	this.context = context;
	
	File outFile = new File(Environment.getExternalStoragePublicDirectory("JYShare"),outputPath);
	InputStream is = new FileInputStream(inputPath);
	FileOutputStream fos = new FileOutputStream(outFile+"_"+versionName+".apk");
	byte[] Buff = new byte[1024];
	
	int fileSize = 0;
	int ReadCount = 0;
	while((ReadCount = is.read(Buff))!=-1)
	{
		fileSize += ReadCount;
		fos.write(Buff, 0, ReadCount);
	}
	is.close();
}
 
Example 9
Project: zabbkit-android   File: GraphFragment.java   View Source Code Vote up 6 votes
private void saveImageFile(Bitmap bitmap) {
    String timeStamp = new SimpleDateFormat(FILE_NAME_TIME_FORMAT,
            Locale.ENGLISH).format(new Date());
    if (bitmap != null) {
        String imageFileName = "ZabbKitGraph_" + timeStamp
                + FILE_NAME_PREFIX;
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File picturesDir = new File(storageDir,
                Constants.ZABBKIT_PICTURES_DIR);
        if (!picturesDir.exists()) {
            if (!picturesDir.mkdirs()) {
                return;
            }
        }
        File imageFile = new File(picturesDir, imageFileName);
        saveImage(bitmap, imageFile);
        galleryAddPic(imageFile.getAbsolutePath());
    }
}
 
Example 10
Project: Matisse-Image-and-Video-Selector   File: MediaStoreCompat.java   View Source Code Vote up 6 votes
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp =
            new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = String.format("JPEG_%s.jpg", timeStamp);
    File storageDir;
    if (mCaptureStrategy.isPublic) {
        storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
    } else {
        storageDir = mContext.get().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }

    // Avoid joining path components manually
    File tempFile = new File(storageDir, imageFileName);

    // Handle the situation that user's external storage is not ready
    if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
        return null;
    }

    return tempFile;
}
 
Example 11
Project: Paprika   File: ImaggaFragment.java   View Source Code Vote up 6 votes
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), "Camera");
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}
 
Example 12
Project: treetracker-android   File: FroyoAlbumDirFactory.java   View Source Code Vote up 5 votes
@Override
public File getAlbumStorageDir(String albumName) {
	// TODO Auto-generated method stub
	return new File(
	  Environment.getExternalStoragePublicDirectory(
	    Environment.DIRECTORY_PICTURES
	  ), 
	  albumName
	);
}
 
Example 13
Project: orgzly-android   File: DirectoryRepoTest.java   View Source Code Vote up 5 votes
@Test
public void testListDownloadsDirectory() throws IOException {
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    String path = DirectoryRepo.SCHEME + ":" + dir.getAbsolutePath();

    DirectoryRepo repo = new DirectoryRepo(path, false);

    assertNotNull(repo.getBooks());
}
 
Example 14
Project: Bailan   File: AppDetailActivity.java   View Source Code Vote up 5 votes
@Override
protected void initData() {
    Intent intent = getIntent();
    packageName = intent.getStringExtra("packageName");
    isMove = intent.getBooleanExtra("isMove", false);
    mHttpDownManager = HttpDownManager.getInstance();
    mHttpDownManager.registerObserver(this);
    mDownUtil = DbDownUtil.getInstance();

    downInfo = mDownUtil.queryDownBy((long) packageName.hashCode());//表示当前任务是否下载过
    if (downInfo == null)
        outFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), packageName + ".apk");
    mPresenter.getAppDetailData(this, packageName);
}
 
Example 15
Project: BloomReader   File: BookCollection.java   View Source Code Vote up 5 votes
public static File getLocalBooksDirectory() throws ExtStorageUnavailableException {
    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        throw new ExtStorageUnavailableException();
    File bloomDir = Environment.getExternalStoragePublicDirectory("Bloom");
    bloomDir.mkdirs();
    return bloomDir;
}
 
Example 16
Project: androidadvanced   File: MainActivity.java   View Source Code Vote up 5 votes
private File getFile() {
    File photoFile = null;
    try {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        photoFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        photoPath = photoFile.getAbsolutePath();
    } catch (IOException ex) {
        Snackbar.make(viewPager, R.string.main_error_dispatch_camera, Snackbar.LENGTH_SHORT).show();
    }
    return photoFile;
}
 
Example 17
Project: Emoji-Fy   File: BitmapUtils.java   View Source Code Vote up 5 votes
static String saveImage(Context context, Bitmap image) {

        String savedImagePath = null;

        // Create the new file in the external storage
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + ".jpg";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        + "/Emojify");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }

        // Save the new Bitmap
        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            savedImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream fOut = new FileOutputStream(imageFile);
                image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add the image to the system gallery
            galleryAddPic(context, savedImagePath);

            // Show a Toast with the save location
            String savedMessage = context.getString(R.string.saved_message, savedImagePath);
            Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
        }

        return savedImagePath;
    }
 
Example 18
Project: LucaHome-AndroidApplication   File: Logger.java   View Source Code Vote up 4 votes
private Logger() {
    _documentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    _debuggingEnabled = true;
    _writeToFileEnabled = true;
    createNewLogFile();
}
 
Example 19
Project: downloadmanager   File: DownloadManager.java   View Source Code Vote up 4 votes
/**
 * Rename the given download if the download has completed
 *
 * @param context     the {@link Context} to use in case need to update MediaProvider
 * @param id          the downloaded id
 * @param displayName the new name to rename to
 * @return true if rename was successful, false otherwise
 * @hide
 */
public boolean rename(Context context, long id, String displayName) {
    if (!StorageUtils.isValidFatFilename(displayName)) {
        throw new SecurityException(displayName + " is not a valid filename");
    }

    Query query = new Query().setFilterById(id);
    Cursor cursor = null;
    String oldDisplayName = null;
    String mimeType = null;
    try {
        cursor = query(query);
        if (cursor == null) {
            return false;
        }
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
            if (DownloadManager.STATUS_SUCCESSFUL != status) {
                return false;
            }
            oldDisplayName = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TITLE));
            mimeType = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    if (oldDisplayName == null || mimeType == null) {
        throw new IllegalStateException(
                "Document with id " + id + " does not exist");
    }

    final File parent = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);

    final File before = new File(parent, oldDisplayName);
    final File after = new File(parent, displayName);

    if (after.exists()) {
        throw new IllegalStateException("Already exists " + after);
    }
    if (!before.renameTo(after)) {
        throw new IllegalStateException("Failed to rename to " + after);
    }

    // Update MediaProvider if necessary
    if (mimeType.startsWith("image/")) {
        context.getContentResolver().delete(Images.Media.EXTERNAL_CONTENT_URI,
                Images.Media.DATA + "=?",
                new String[]{
                        before.getAbsolutePath()
                });

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(after));
        context.sendBroadcast(intent);
    }

    ContentValues values = new ContentValues();
    values.put(Downloads.Impl.COLUMN_TITLE, displayName);
    values.put(Downloads.Impl._DATA, after.toString());
    values.putNull(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
    long[] ids = {id};

    return (mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
            getWhereArgsForIds(ids)) == 1);
}
 
Example 20
Project: hypertrack-live-android   File: EasyImageFiles.java   View Source Code Vote up 4 votes
static File publicRootDir() {
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}