下面列出了android.content.Context#getExternalFilesDir ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public PcmPlayer(Context context, Handler handler) {
this.mContext = context;
this.audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, wBufferSize, AudioTrack.MODE_STREAM);
this.handler = handler;
audioTrack.setPlaybackPositionUpdateListener(this, handler);
cacheDir = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
}
public static String defaultFolder(Context context) {
String folder;
File externalFolder = context.getExternalFilesDir(null);
if (externalFolder != null && Device.isKitKatApi()) {
folder = externalFolder.getAbsolutePath();
} else {
folder = Environment.getExternalStorageDirectory().getAbsolutePath();
}
//folder = context.getExternalFilesDir(null).getAbsolutePath();
//folder = Environment.getExternalStorageDirectory().getAbsolutePath();
return folder;
}
private File getDirectory(String directory) {
Context c = bridge.getContext();
switch(directory) {
case "APPLICATION":
return c.getFilesDir();
case "DOCUMENTS":
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
case "DATA":
return c.getFilesDir();
case "CACHE":
return c.getCacheDir();
case "EXTERNAL":
return c.getExternalFilesDir(null);
case "EXTERNAL_STORAGE":
return Environment.getExternalStorageDirectory();
}
return null;
}
/**
* 拷贝文件到图片缓存中
*
* @param fileName 原文件名
* @param time 新文件名
*/
private static String[] saveBitmap(Context context, File[] fileName, long time) {
File_Image_Saved = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator;
String[] images = new String[fileName.length];
for (int i = 0; i < fileName.length; i++) {
File source = fileName[i];
String dest = File_Image_Saved + String.valueOf(time) + "_" + i;
Log.i(TAG, "saveBitmap: dest: " + dest);
images[i] = dest;
try (FileChannel inputChannel = new FileInputStream(source).getChannel();
FileChannel outputChannel = new FileOutputStream(dest).getChannel()) {
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (IOException e) {
e.printStackTrace();
}
}
return images;
}
/**
* Set the local destination for the downloaded file to a path within
* the application's external files directory (as returned by
* {@link Context#getExternalFilesDir(String)}.
* <p>
* The downloaded file is not scanned by MediaScanner. But it can be
* made scannable by calling {@link #allowScanningByMediaScanner()}.
*
* @param context the {@link Context} to use in determining the external
* files directory
* @param dirType the directory type to pass to
* {@link Context#getExternalFilesDir(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 setDestinationInExternalFilesDir(Context context, String dirType,
String subPath) {
final File file = context.getExternalFilesDir(dirType);
if (file == null) {
throw new IllegalStateException("Failed to get external storage files 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;
}
@TargetApi(8)
private static File getExternalFilesDir(Context context) {
if (hasFroyo()) {
File dir1 = context.getExternalFilesDir((String) null);
return dir1 != null ? dir1 : context.getFilesDir();
} else {
String dir = "/Android/content/" + context.getPackageName() + "/files";
return new File(Environment.getExternalStorageDirectory(), dir);
}
}
/**
* 这里的文件夹已经被创建过了
*
* @param context
* @param ignoreSDRemovable 可移除的sd是否无视
* @return
*/
public static File getSmartFilesDir(Context context, boolean ignoreSDRemovable) {
//SD卡 存在 并且不是 拔插的
File fileResult=context.getFilesDir();
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&&(ignoreSDRemovable || Environment.isExternalStorageRemovable())){
File fileTemp= context.getExternalFilesDir(null);
if(fileTemp!=null)
fileResult=fileTemp;//导致即使不为Null的可能
}
return fileResult;
}
/**
* 获取缓存图片的目录
*
* @param context Context
* @return 缓存图片的目录
*/
public static String getImageCacheDir(Context context) {
File file;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
} else {
file = context.getCacheDir();
}
String path = file.getPath() + "/cache";
File cachePath = new File(path);
if (!cachePath.exists())
cachePath.mkdir();
return path;
}
/**
* @param context 上下文
* @return 获取app私有目录
*/
public static File getPickerFileDirectory(Context context) {
File file = new File(context.getExternalFilesDir(null), ImagePicker.DEFAULT_FILE_NAME);
if (!file.exists()) {
if (file.mkdirs()) {
return file;
}
}
return file;
}
private boolean makeDirectoryInPrivateStorage(Context context, String directoryName) {
File randomDirectory = new File(context.getExternalFilesDir(null) + File.separator + directoryName);
if (!randomDirectory.exists()) {
System.out.println("creating directory: " + directoryName);
randomDirectory.mkdir();
}
return true;
}
/**
* 获取日志路径
*/
public static File getLogDir(Context context) {
if (isSDCardMounted()) {
return context.getExternalFilesDir("log");
} else {
return new File(context.getFilesDir(), "log");
}
}
public static File getAttachmentDir(Context mContext) {
return mContext.getExternalFilesDir(null);
}
public static File getExternalFilesDir(Context context, String type) {
return context.getExternalFilesDir(type);
}
public static boolean isAutotestOnStart(Context context)
{
final File cfgFile = new File(context.getExternalFilesDir(null), TEST_CONFIGURATION);
return cfgFile.exists();
}
private static File saveBitmapToPublicStorage(final Context context, final String filenameWithoutExtension, final Bitmap bitmap, final int format) throws Exception {
// get the output directory
final File applicationDir = context.getExternalFilesDir(null);
final File libraryDir = new File(applicationDir, "im.delight.android.commons");
final File outputDir = new File(libraryDir, "screenshots");
// create the output directory if it doesn't exist
outputDir.mkdirs();
// create the .nomedia file which prevents images from showing up in gallery
try {
final File noMedia = new File(outputDir, NO_MEDIA_FILENAME);
noMedia.createNewFile();
}
// ignore if the file does already exist or cannot be created
catch (Exception e) { }
// set up variables for file format
final Bitmap.CompressFormat bitmapFormat;
final String fileExtension;
if (format == FORMAT_JPEG) {
bitmapFormat = Bitmap.CompressFormat.JPEG;
fileExtension = ".jpg";
}
else if (format == FORMAT_PNG) {
bitmapFormat = Bitmap.CompressFormat.PNG;
fileExtension = ".png";
}
else {
throw new Exception("Unknown format: "+format);
}
// get a reference to the new file
final File outputFile = new File(outputDir, filenameWithoutExtension + fileExtension);
// if the output file already exists
if (outputFile.exists()) {
// delete it first
outputFile.delete();
}
// create an output stream for the new file
final FileOutputStream outputStream = new FileOutputStream(outputFile);
// write the data to the new file
bitmap.compress(bitmapFormat, 90, outputStream);
// flush the output stream
outputStream.flush();
// close the output stream
outputStream.close();
// return the file reference
return outputFile;
}
/**
* Get a temp file.
*
* @param file The base file for which to create a temp file.
* @return The temp file.
*/
public static File getTempFile(@NonNull final File file, Context context) {
File extDir = context.getExternalFilesDir(null);
return new File(extDir, file.getName());
}
private DebugLog(Context context) {
mLogFile = new File(context.getExternalFilesDir(null), LOG_FILENAME);
mFileStatus = STATUS_UNINITIALIZED;
mWriteStatus = STATUS_UNINITIALIZED;
mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
/**
* save the Bitmap to SDCard
* @param context context
* @param bitmap bitmap
* @return filePath
*/
public static String saveBitmapToSDCard(Context context, Bitmap bitmap) {
if (null == context) {
return null;
}
if (null == bitmap) {
ToastUtil.showToast(context, R.string.share_save_bitmap_failed, true);
return null;
}
//SDCard is valid
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
ToastUtil.showToast(context, R.string.share_save_bitmap_no_sdcard, true);
return null;
}
String filePath = null;
File externalFilesDir = context.getExternalFilesDir(null);
String dir = null;
if (null != externalFilesDir) {
dir = externalFilesDir.getAbsolutePath();
}
String packageName = context.getPackageName();
if (!TextUtils.isEmpty(dir)) {
if (!dir.endsWith(File.separator)) {
filePath = dir + File.separator + packageName + "_share_pic.png";
} else {
filePath = dir + packageName + "_share_pic.png";
}
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
ToastUtil.showToast(context, e.getMessage(), true);
}
}
return filePath;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = DEVICE_ROOT;
} else if (TAG_FILES_PATH.equals(tag)) {
target = context.getFilesDir();
} else if (TAG_CACHE_PATH.equals(tag)) {
target = context.getCacheDir();
} else if (TAG_EXTERNAL.equals(tag)) {
target = Environment.getExternalStorageDirectory();
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
File[] externalFilesDirs;
if (Build.VERSION.SDK_INT >= 19) {
externalFilesDirs = context.getExternalFilesDirs(null);
} else {
externalFilesDirs = new File[] { context.getExternalFilesDir(null) };
}
if (externalFilesDirs.length > 0) {
target = externalFilesDirs[0];
}
} else if (TAG_EXTERNAL_CACHE.equals(tag)) {
File[] externalCacheDirs;
if (Build.VERSION.SDK_INT >= 19) {
externalCacheDirs = context.getExternalCacheDirs();
} else {
externalCacheDirs = new File[] { context.getExternalCacheDir() };
}
if (externalCacheDirs.length > 0) {
target = externalCacheDirs[0];
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& TAG_EXTERNAL_MEDIA.equals(tag)) {
File[] externalMediaDirs = context.getExternalMediaDirs();
if (externalMediaDirs.length > 0) {
target = externalMediaDirs[0];
}
}
if (target != null) {
strat.addRoot(name, buildPath(target, path));
}
}
}
return strat;
}
public static File getAppFolder(Context c) {
if (sBaseAppFolder == null) {
sBaseAppFolder = c.getExternalFilesDir(null);
}
return sBaseAppFolder;
}