下面列出了android.os.Environment#getExternalStoragePublicDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
/**
* 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;
}
/**
* 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();
}
/**
* 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();
}
/**
* 获取保存图片的目录
*
* @return
*/
public static File getAlbumDir() {
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getAlbumName());
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
@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();
}
}
@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(); }
}
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);
}
@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);
}
}
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");
}
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();
}
}
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;
}
@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();
}
public static File getAndroidMoviesFolder() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
}
@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);
}
public static String getPlayFolderPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
File.separator + SNAPSHOT_FOLDER_NAME_EVERCAM + File.separator +
SNAPSHOT_FOLDER_NAME_PLAY;
}
public DownloaderConfig() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
this.saveDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
this.threadNum = DEFAULT_THREAD_NUM;
}
/**
* 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);
}