下面列出了怎么用android.os.Environment的API类实例代码及写法,或者点击链接到github查看源代码。
private void preparePhotoForShare() {
final Bitmap[] image = new Bitmap[1];
new Thread(new Runnable() {
@Override
public void run() {
try {
image[0] = Picasso.with(getContext())
.load(photos.get(currentPosition).getImageUrl())
.get();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image[0].compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image_temp.jpg");
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
sendPhotoForShare();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void createDirectoryAndSaveFile(PdfWriter imageToSave, String fileName) throws FileNotFoundException {
File direct = new File(Environment.getExternalStorageDirectory() + "/TutorialesHackro");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/TutorialesHackro/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/TutorialesHackro/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("edwq",e.getMessage());
}
}
private static File getExternalCacheDir(Context context) {
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
L.w("Unable to create external cache directory");
return null;
}
try {
new File(appCacheDir, ".nomedia").createNewFile();
} catch (IOException e) {
L.i("Can't create \".nomedia\" file in application external cache directory");
}
}
return appCacheDir;
}
@OnClick(R.id.download_button)
public void downloadImage() {
String imageUrl = imageUrlList.get(imageViewPager.getCurrentItem());
String fileName = StringUtils.getImageNameFromUrl(imageUrl);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/scallop";
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(fileName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(path, fileName);
downloadManager.enqueue(request);
}
public String getStoragePath()
{
String s = Environment.getExternalStorageState();
Debug.i("BraceletApp", (new StringBuilder()).append("ext state =").append(s).toString());
File file;
if ("mounted".equals(s))
{
file = getExternalFilesDir("Millelet");
} else
{
file = getFilesDir();
}
if (file == null)
{
file = getFilesDir();
}
if (file == null)
{
return (new StringBuilder()).append(Environment.getExternalStorageDirectory().getPath()).append("/").append("Millelet").toString();
} else
{
String s1 = file.getPath();
Debug.i("BraceletApp", (new StringBuilder()).append("getStoragePath:").append(s1).toString());
return s1;
}
}
/**
* 刷新视频文件
*
* @param reScan true: 重新扫描整个系统目录
* false: 只查询数据库数据
*/
@Override
public void refreshVideo(Context context, boolean reScan) {
//通知系统刷新目录
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
if (context != null)
context.sendBroadcast(intent);
if (reScan) {
refreshAllVideo();
} else {
refreshDatabaseVideo();
}
EventBus.getDefault().post(new UpdateFolderDanmuEvent());
}
/**
* 计算SD卡的剩余空间
*
* @return 返回-1,说明没有安装sd卡
*/
public static long getFreeDiskSpace() {
String status = Environment.getExternalStorageState();
long freeSpace = 0;
if (status.equals(Environment.MEDIA_MOUNTED)) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
freeSpace = availableBlocks * blockSize / 1024;
} catch (Exception e) {
e.printStackTrace();
}
} else {
return -1;
}
return (freeSpace);
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
}
}
/**
* Initializes the disk cache when is closed or null.
*
* @param context the application context.
*/
private static void intDiskCacheIfNeeded(Context context) {
if (DISK_CACHE == null || DISK_CACHE.isClosed()) {
try {
long size = 1024 * 1024 * 10;
String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || Files.isExternalStorageRemovable()
? Files.getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
File file = new File(cachePath + File.separator + IMAGE_CACHE_DIR);
DISK_CACHE = DiskLruCache.open(file, 1, 1, size); // Froyo sometimes fails to initialize
} catch (IOException ex) {
Log.e(TAG, "Couldn't init disk cache", ex);
}
}
}
/**
* Init crash log cache directory.
*
* @param application application
* @param crashDirPath crash log file cache directory
*/
private static void initCacheDir(Application application, final String crashDirPath) {
if (StringUtils.isSpace(crashDirPath)) {
dir = null;
} else {
dir = crashDirPath.endsWith(FILE_SEP) ? crashDirPath : crashDirPath + FILE_SEP;
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& application.getExternalCacheDir() != null) {
// defaultDir: /android/data/< package name >/cache/crash/...
defaultDir = application.getExternalCacheDir() + FILE_SEP + "crash" + FILE_SEP;
} else {
// defaultDir: /data/data/< package name >/cache/crash/...
defaultDir = application.getCacheDir() + FILE_SEP + "crash" + FILE_SEP;
}
}
/**
* Determine if a file or directory exists.
* @param name The name of the file to check.
* @return T=exists, F=not found
*/
public static boolean testFileExists(String name) {
boolean status;
// If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists();
}
// If no SD card
else {
status = false;
}
return status;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rs = RenderScript.create(this);
try {
AssetManager assetManager = getAssets();
String[] fileList = assetManager.list(modelPath);
if (fileList.length != 0){
detector = new MobileNetSSD(rs, assetManager, modelPath);
}
else {
String modelDir = Environment.getExternalStorageDirectory().getPath() + "/" + modelPath;
detector = new MobileNetSSD(rs, null, modelDir);
}
} catch (IOException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
if (methodMap == null) {
throw new NullPointerException("methodMap is null");
}
mMethodMap = methodMap;
final File systemDir = userId == UserHandle.USER_OWNER
? new File(Environment.getDataDirectory(), SYSTEM_PATH)
: Environment.getUserSystemDirectory(userId);
final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
if (!inputMethodDir.mkdirs()) {
Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
}
final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile);
if (!subtypeFile.exists()) {
// If "subtypes.xml" doesn't exist, create a blank file.
writeAdditionalInputMethodSubtypes(
mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
} else {
readAdditionalInputMethodSubtypes(
mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
}
}
@Override
public File[] getExternalFilesDirs(String type) {
synchronized (mSync) {
if (mExternalFilesDirs == null) {
mExternalFilesDirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
}
// Splice in requested type, if any
File[] dirs = mExternalFilesDirs;
if (type != null) {
dirs = Environment.buildPaths(dirs, type);
}
// Create dirs if needed
return ensureDirsExistOrFilter(dirs);
}
}
public static File getCacheDirectory(Context context, boolean preferExternal) {
File appCacheDir = null;
String externalStorageState;
try {
externalStorageState = Environment.getExternalStorageState();
} catch (NullPointerException e) {
externalStorageState = "";
}
if (preferExternal && "mounted".equals(externalStorageState) && hasExternalStoragePermission(context)) {
appCacheDir = getExternalCacheDir(context);
}
if (appCacheDir == null) {
appCacheDir = context.getCacheDir();
}
if (appCacheDir != null) {
return appCacheDir;
}
L.w("Can't define system cache directory! '%s' will be used.", "/data/data/" + context.getPackageName() + "/cache/");
return new File("/data/data/" + context.getPackageName() + "/cache/");
}
/**
* http://developer.android.com/training/camera/photobasics.html
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory()
+ "/TessOCR";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private static File getExternalCacheDir(Context context) {
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
L.w("Unable to create external cache directory");
return null;
}
try {
new File(appCacheDir, ".nomedia").createNewFile();
} catch (IOException e) {
L.i("Can't create \".nomedia\" file in application external cache directory");
}
}
return appCacheDir;
}
byte[] read4k(){
try {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/AUAVtmp/fullPic.JPG");
//File file = new File("../tmp/pictmp.jpg");
FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
pic = new byte[buffer.capacity()];
while(buffer.hasRemaining()){
int remaining = pic.length;
if(buffer.remaining() < remaining){
remaining = buffer.remaining();
}
buffer.get(pic, 0, remaining);
}
return pic;
} catch(Exception e){
e.printStackTrace();
}
return new byte[0];
}
/**
* gets storage state and current cache size
*/
private void updateStorageInfo(){
long cacheSize = updateStoragePreferences(this);
//cache management ends here
TextView tv = findViewById(R.id.sdcardstate_value);
final String state = Environment.getExternalStorageState();
boolean mSdCardAvailable = Environment.MEDIA_MOUNTED.equals(state);
tv.setText((mSdCardAvailable ? "Mounted" : "Not Available") );
if (!mSdCardAvailable) {
tv.setTextColor(Color.RED);
tv.setTypeface(null, Typeface.BOLD);
}
tv = findViewById(R.id.version_text);
tv.setText(BuildConfig.VERSION_NAME + " " + BuildConfig.BUILD_TYPE);
tv = findViewById(R.id.mainstorageInfo);
tv.setText(Configuration.getInstance().getOsmdroidTileCache().getAbsolutePath() + "\n" +
"Cache size: " + Formatter.formatFileSize(this,cacheSize));
}
private File initVideoFile() {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
if (!dir.exists()) {
dir.mkdirs();
}
if (!dir.exists()) {
dir = mDemoView.getActivity().getCacheDir();
}
return new File(dir, String.format("photo_movie_%s.mp4",
new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(System.currentTimeMillis())));
}
public void downloadFile(View v){
if(gInstance.fileName.equals("")){
MainActivity.showMessage("Missing file!", this);
return;
}
String url=MainActivity.WEBSITE +"/"+ gInstance.media;
try{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(gInstance.fileName);
request.setDescription(MainActivity.WEBSITE);
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); only download thro wifi.
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
}
};
manager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}catch(Exception e){
MainActivity.showMessage(e.getMessage(), this);
}
}
/** 判断SD卡是否挂载 */
public static boolean isSDCardAvailable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return true;
} else {
return false;
}
}
/**
* 获得机身可用内存
*
* @return
*/
private String getRomAvailableSize()
{
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(SimpleActivity.this, blockSize * availableBlocks);
}
/**
* 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 = buildPath(DEVICE_ROOT, path);
} else if (TAG_FILES_PATH.equals(tag)) {
target = buildPath(context.getFilesDir(), path);
} else if (TAG_CACHE_PATH.equals(tag)) {
target = buildPath(context.getCacheDir(), path);
} else if (TAG_EXTERNAL.equals(tag)) {
target = buildPath(Environment.getExternalStorageDirectory(), path);
}
if (target != null) {
strat.addRoot(name, target);
}
}
}
return strat;
}
/**
* SD卡是否可用
*
* @return true:可用,false:不可用
*/
public static boolean isCanUseSD() {
try {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean isExternalStorageReadable() {
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
/**
* date: 7/12/17
* author: chenli
* description: 利用系统的下载服务
*/
private void downLoadFile(String url, String contentDisposition, String mimetype) {
//创建下载任务,downloadUrl就是下载链接
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//指定下载路径和下载文件名
request.setDestinationInExternalPublicDir("/download/", URLUtil.guessFileName(url, contentDisposition, mimetype));
//获取下载管理器
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//将下载任务加入下载队列,否则不会进行下载
if (downloadManager != null) downloadManager.enqueue(request);
ToastUtils.showToast(BaseApplication.getContext(),
"下载完成:" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath() + File.separator + URLUtil.guessFileName(url, contentDisposition, mimetype));
}
/**
* 外置存储卡的路径
*
* @return
*/
public static String getExternalStorePath() {
if (isExistExternalStore()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
public static void download(Context ctx, String url, String filename) {
String authCookie = OkHttpHelper.getInstance().getAuthCookie();
if (TextUtils.isEmpty(url) || TextUtils.isEmpty(filename)
|| (url.contains(HiUtils.ForumUrlPattern) && TextUtils.isEmpty(authCookie))) {
UIUtils.toast("下载信息不完整,无法进行下载");
return;
}
if (UIUtils.askForStoragePermission(ctx)) {
return;
}
if (DownloadManagerResolver.resolve(ctx)) {
DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.addRequestHeader("User-agent", HiUtils.getUserAgent());
if (url.contains(HiUtils.ForumUrlPattern)) {
req.addRequestHeader("Cookie", "cdb_auth=" + authCookie);
}
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
if (filename.toLowerCase().endsWith(".apk"))
req.setMimeType("application/vnd.android.package-archive");
dm.enqueue(req);
}
}
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);
}