android.os.Environment#getExternalStoragePublicDirectory ( )源码实例Demo

下面列出了android.os.Environment#getExternalStoragePublicDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: apkExtractor   文件: Extractor.java
public String extractWithoutRoot(PackageInfo info) throws Exception {
	File src = new File(info.applicationInfo.sourceDir);
	File dst;
	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
		dst = new File(Environment.getExternalStorageDirectory(), get_out_filename(info));
	} else {
		dst = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),  get_out_filename(info));
	}
	dst = buildDstPath(dst);
	try {
		copy(src, dst);
	} catch (IOException ex) {
		throw new Exception(ex.getMessage());
	}
	if (!dst.exists()) {
		throw new Exception("cannot extract file [no root]");
	}
	return dst.toString();
}
 
源代码2 项目: android-project-wo2b   文件: DownloadManager.java
/**
 * Set the local destination for the downloaded file to a path within
 * the public external storage directory (as returned by
 * {@link Environment#getExternalStoragePublicDirectory(String)}).
 * <p>
 * The downloaded file is not scanned by MediaScanner. But it can be
 * made scannable by calling {@link #allowScanningByMediaScanner()}.
 *
 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
 * @param subPath the path within the external directory, including the
 *            destination filename
 * @return this object
 * @throws IllegalStateException If the external storage directory
 *             cannot be found or created.
 */
public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
    File file = Environment.getExternalStoragePublicDirectory(dirType);
    if (file == null) {
        throw new IllegalStateException("Failed to get external storage public directory");
    } else if (file.exists()) {
        if (!file.isDirectory()) {
            throw new IllegalStateException(file.getAbsolutePath() +
                    " already exists and is not a directory");
        }
    } else {
        if (!file.mkdirs()) {
            throw new IllegalStateException("Unable to create directory: "+
                    file.getAbsolutePath());
        }
    }
    setDestinationFromBase(file, subPath);
    return this;
}
 
源代码3 项目: 365browser   文件: TracingControllerAndroid.java
/**
 * Generates a unique filename to be used for tracing in the Downloads directory.
 */
@CalledByNative
private static String generateTracingFilePath() {
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        return null;
    }

    // Generate a hopefully-unique filename using the UTC timestamp.
    // (Not a huge problem if it isn't unique, we'll just append more data.)
    SimpleDateFormat formatter = new SimpleDateFormat(
            "yyyy-MM-dd-HHmmss", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    File dir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    File file = new File(
            dir, "chrome-profile-results-" + formatter.format(new Date()));
    return file.getPath();
}
 
源代码4 项目: ImageEditor-android   文件: MainActivity.java
/**
 * Try to create the required folder on the sdcard where images will be
 * saved to.
 * 
 * @return
 */
private File createFolders() {

	File baseDir;

	if (android.os.Build.VERSION.SDK_INT < 8) {
		baseDir = Environment.getExternalStorageDirectory();
	} else {
		baseDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
	}

	if (baseDir == null)
		return Environment.getExternalStorageDirectory();

	Log.d(LOG_TAG, "Pictures folder: " + baseDir.getAbsolutePath());
	File fotorSDKFolder = new File(baseDir, FOLDER_NAME);

	if (fotorSDKFolder.exists())
		return fotorSDKFolder;
	if (fotorSDKFolder.mkdirs())
		return fotorSDKFolder;

	return Environment.getExternalStorageDirectory();
}
 
源代码5 项目: AndroidBase   文件: ImageUtils.java
/**
 * 获取保存图片的目录
 *
 * @return
 */
public static File getAlbumDir() {
    File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getAlbumName());
    if (!dir.exists()) {
        dir.mkdirs();
    }
    return dir;
}
 
源代码6 项目: Kandroid   文件: TaskDetailActivity.java
@Override
        public void onDownloadTaskFile(boolean success, int id, String data) {
            if (success) {
                byte[] inData = Base64.decode(data, Base64.DEFAULT);
                for (KanboardTaskFile f: files) {
                    if (f.getId() == id) {
                        try {
                            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), f.getName());
                            FileOutputStream outData = new FileOutputStream(file);
                            outData.write(inData);
                            outData.close();
                            String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()));
                            if (mime == null) {
                                mime = "application/octet-stream";
                            }
                            if (BuildConfig.DEBUG) {
                                Log.d(Constants.TAG, Uri.fromFile(file).toString());
                                Log.d(Constants.TAG, mime);
                            }
                            DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                            dm.addCompletedDownload(file.getName(), "Kandroid download", false, mime, file.getPath(), file.length(), true);
//                            Snackbar.make(findViewById(R.id.root_layout), String.format(Locale.getDefault(), "Saved file to: %s", file.getPath()), Snackbar.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.w(Constants.TAG, "IOError writing file");
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            } else {
                Snackbar.make(findViewById(R.id.root_layout), "Unable to download file", Snackbar.LENGTH_LONG).show();
            }
        }
 
源代码7 项目: WhatsAppBetaUpdater   文件: UtilsAsync.java
@Override
protected void onPreExecute() {
    super.onPreExecute();
    path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";

    // Configure cancel button and show progress dialog
    MaterialDialog.Builder builder = UtilsDialog.showDownloadingDialog(context, downloadType, update.getLatestVersion());
    builder.onNegative(new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(MaterialDialog dialog, DialogAction which) {
            cancel(true);
        }
    });
    dialog = builder.show();

    // Configure type of download: WhatsApp update or Beta Updater update
    switch (downloadType) {
        case WHATSAPP_APK:
            filename = "WhatsApp_" + update.getLatestVersion() + ".apk";
            downloadUrl = update.getDownloadUrl();
            break;
        case UPDATE:
            filename = context.getPackageName() + "_" + update.getLatestVersion() + ".apk";
            downloadUrl = Config.GITHUB_APK + "v" + update.getLatestVersion() + "/" + context.getPackageName() + ".apk";
            break;
    }

    // Create download directory if doesn't exist
    File file = new File(path);
    if (!file.exists()) { file.mkdir(); }

}
 
源代码8 项目: Luban-Circle-Demo   文件: FileUtils.java
public static File createTmpFile(Context context) throws IOException{
    File dir = null;
    if(TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) {
        dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (!dir.exists()) {
            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera");
            if (!dir.exists()) {
                dir = getCacheDirectory(context, true);
            }
        }
    }else{
        dir = getCacheDirectory(context, true);
    }
    return File.createTempFile(JPEG_FILE_PREFIX, JPEG_FILE_SUFFIX, dir);
}
 
源代码9 项目: delion   文件: OMADownloadHandler.java
@Override
protected void onPostExecute(Boolean success) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    if (success) {
        String path = mDownloadInfo.getFilePath();
        if (!TextUtils.isEmpty(path)) {
            // Move the downloaded content from the app directory to public directory.
            File fromFile = new File(path);
            String fileName = fromFile.getName();
            File toFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), fileName);
            if (fromFile.renameTo(toFile)) {
                manager.addCompletedDownload(
                        fileName, mDownloadInfo.getDescription(), false,
                        mDownloadInfo.getMimeType(), toFile.getPath(),
                        mDownloadInfo.getContentLength(), true);
            } else if (fromFile.delete()) {
                Log.w(TAG, "Failed to rename the file.");
                return;
            } else {
                Log.w(TAG, "Failed to rename and delete the file.");
            }
        }
        showNextUrlDialog(mOMAInfo);
    } else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
        // Remove the downloaded content.
        manager.remove(mDownloadId);
    }
}
 
源代码10 项目: MultiMediaSample   文件: Camera2Fragment.java
private File getOutputMediaFile(){
    //get the mobile Pictures directory
    File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    //get the current time
    String timeStamp = new SimpleDateFormat("yyyy-MMdd-HHmmss").format(new Date());
    return new File(picDir.getPath() + File.separator + "hejunlin_camera2_"+ timeStamp + ".jpg");
}
 
源代码11 项目: codeexamples-android   文件: ExternalStorage.java
void deleteExternalStoragePublicPicture() {
    // Create a path where we will place our picture in the user's
    // public pictures directory and delete the file.  If external
    // storage is not currently mounted this will fail.
    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File file = new File(path, "DemoPicture.jpg");
    file.delete();
}
 
private void createImageGallery() {
    File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    mGalleryFolder = new File(storageDirectory, GALLERY_LOCATION);
    if(!mGalleryFolder.exists()) {
        mGalleryFolder.mkdirs();
    }

}
 
源代码13 项目: fastnfitness   文件: ImageUtil.java
private File createImageFile(Fragment pF) throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = null;

    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        return null;
    } else {
        //We use the FastNFitness directory for saving our .csv file.
        storageDir = Environment.getExternalStoragePublicDirectory("/FastnFitness/DCIM/");
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
    }
    //File storageDir = pF.getActivity().getExternalFilesDir(Environment.DIRECTORY_DCIM);
    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;
}
 
源代码14 项目: Spectaculum   文件: Utils.java
@Override
public void onFrameCaptured(Bitmap bitmap) {
    File targetFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            mFileNamePrefix + System.currentTimeMillis() + ".png");
    if(Utils.saveBitmapToFile(bitmap, targetFile)) {
        Toast.makeText(mContext, "Saved frame to " + targetFile.getPath(),
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(mContext, "Failed saving frame", Toast.LENGTH_LONG).show();
    }
}
 
private String getExternalStoragePath() {
  File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
  return f.getAbsolutePath();
}
 
源代码16 项目: GPUVideo-android   文件: BaseCameraActivity.java
public static File getAndroidMoviesFolder() {
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
}
 
源代码17 项目: ESeal   文件: UpdateDialogActivity.java
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContext = this;
        @LayoutRes int layoutId = UpdateSP.getDialogLayout();
        if (layoutId > 0) {
            setContentView(layoutId);
        } else {
            setContentView(ResourceUtils.getResourceIdByName(mContext, "layout", "jjdxm_update_dialog"));
        }
        Intent intent = getIntent();
        mUpdate = (Update) intent.getSerializableExtra(UpdateConstants.DATA_UPDATE);
        mAction = intent.getIntExtra(UpdateConstants.DATA_ACTION, 0);
        mPath = intent.getStringExtra(UpdateConstants.SAVE_PATH);
        String updateContent = null;
        jjdxm_update_wifi_indicator = findViewById(ResourceUtils.getResourceIdByName(mContext, "id", "jjdxm_update_wifi_indicator"));
        jjdxm_update_content = (TextView) findViewById(ResourceUtils.getResourceIdByName(mContext, "id", "jjdxm_update_content"));
        jjdxm_update_id_check = (CheckBox) findViewById(ResourceUtils.getResourceIdByName(mContext, "id", "jjdxm_update_id_check"));
        jjdxm_update_id_ok = (Button) findViewById(ResourceUtils.getResourceIdByName(mContext, "id", "jjdxm_update_id_ok"));
        jjdxm_update_id_cancel = (Button) findViewById(ResourceUtils.getResourceIdByName(mContext, "id", "jjdxm_update_id_cancel"));
        if (jjdxm_update_wifi_indicator != null) {
            if (NetworkUtil.isConnectedByWifi()) {
                //WiFi环境
                jjdxm_update_wifi_indicator.setVisibility(View.INVISIBLE);
            } else {
                jjdxm_update_wifi_indicator.setVisibility(View.VISIBLE);
            }
        }
        if (TextUtils.isEmpty(mPath)) {
            String url = mUpdate.getUpdateUrl();

//            mPath = DownloadManager.getInstance(mContext).getDownPath() + File.separator + url.substring(url.lastIndexOf("/") + 1, url.length());

            File docDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            docDir.mkdir();

            mPath = docDir.getAbsolutePath() + File.separator + url.substring(url.lastIndexOf("/") + 1, url.length());
        }
        if (mAction == 0) {
            DownloadModel dd = DownloadManager.getInstance(mContext).getDownloadByUrl(mUpdate.getUpdateUrl());
            if (dd != null) {
                finshDown = (dd.getDOWNLOAD_STATE() == ParamsManager.State_FINISH);
                File fil = new File(mPath);
                if (finshDown && fil.exists() && (fil.length() + "").equals(dd.getDOWNLOAD_TOTALSIZE())) {
                    finshDown = true;
                } else {
                    finshDown = false;
                }
            }
        } else {
            finshDown = true;
        }
        if (finshDown) {
            //完成下载
            if (mUpdate.getApkSize() > 0) {
                text = getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_dialog_installapk")) + "";
            } else {
                text = "";
            }
            updateContent = getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_newversion"))
                    + mUpdate.getVersionName() + "\n"
                    + text + "\n\n"
                    + getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_updatecontent")) + "\n" + mUpdate.getUpdateContent() +
                    "\n";
            jjdxm_update_id_ok.setText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_installnow"));
            jjdxm_update_content.setText(updateContent);
        } else {
            //有更新下载
            if (mUpdate.getApkSize() > 0) {
                text = getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_targetsize")) + FileUtils.HumanReadableFilesize(mUpdate.getApkSize());
            } else {
                text = "";
            }
            updateContent = getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_newversion"))
                    + mUpdate.getVersionName() + "\n"
                    + text + "\n\n"
                    + getText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_updatecontent")) + "\n" + mUpdate.getUpdateContent() +
                    "\n";
            jjdxm_update_id_ok.setText(ResourceUtils.getResourceIdByName(mContext, "string", "jjdxm_update_updatenow"));
            jjdxm_update_content.setText(updateContent);
        }
        if (jjdxm_update_id_check != null) {
            if (UpdateHelper.getInstance().getUpdateType() == UpdateType.checkupdate) {
                //手动更新
                jjdxm_update_id_check.setVisibility(View.GONE);
            } else {
                jjdxm_update_id_check.setVisibility(UpdateSP.isForced() ? View.GONE : View.VISIBLE);
            }
        }

        if (jjdxm_update_id_check != null) {
            jjdxm_update_id_check.setOnCheckedChangeListener(this);
        }
        jjdxm_update_id_ok.setOnClickListener(this);
        jjdxm_update_id_cancel.setOnClickListener(this);
    }
 
源代码18 项目: evercam-android   文件: SnapshotManager.java
public static String getPlayFolderPath() {
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
            File.separator + SNAPSHOT_FOLDER_NAME_EVERCAM + File.separator +
            SNAPSHOT_FOLDER_NAME_PLAY;
}
 
源代码19 项目: EasyFileDownloader   文件: DownloaderConfig.java
public DownloaderConfig() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        this.saveDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    }
    this.threadNum = DEFAULT_THREAD_NUM;
}
 
源代码20 项目: Album   文件: AlbumUtils.java
/**
 * Generate a random jpg file path.
 *
 * @return file path.
 *
 * @deprecated use {@link #randomJPGPath(Context)} instead.
 */
@NonNull
@Deprecated
public static String randomJPGPath() {
    File bucket = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    return randomJPGPath(bucket);
}