StorageUtil

Posted adamli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了StorageUtil相关的知识,希望对你有一定的参考价值。

package com.android.demo.lileidemo.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import com.android.demo.lileidemo.constant.AppConstants;

import java.io.File;

/**
* date: 04/08/2020.
* author: lilei.
*/
public class StorageUtil {
private static final String TAG = AppConstants.APP_TAG + "StorageUtil ";
private static final boolean DEBUG = false;
private static volatile StorageUtil mInstance;

public static StorageUtil getInstance() {
if (null == mInstance) {
synchronized (StorageUtil.class) {
if (null == mInstance) {
mInstance = new StorageUtil();
}
}
}
return mInstance;
}

public String checkSD(Context contect) {

File data = new File("/data");
Environment.getDataDirectory(); //获得data的路径
StatFs data_stat = new StatFs(data.getPath()); //创建StatFs对象
Log.d(TAG, "checkSD() data.getPath():" + data.getPath());
long data_blockSize = data_stat.getBlockSize(); //获取block的size
float data_totalBlocks = data_stat.getBlockCount();//获取block的个数
float data_totalInMb = (float) ((data_blockSize * data_totalBlocks) / 1024 / 1024);//计算总容量
long data_availableBlocks = data_stat.getAvailableBlocks(); //获取可用block的个数
float data_available = (float) ((data_blockSize * data_availableBlocks) / 1024 / 1024);//计算可用容量
String notice = "FLASH使用情况: 总容量:" + data_totalInMb + "M. 已用:" + (data_totalInMb - data_available + " 可用:" + data_available + "M.");
//很多情况下data分区就是sdcard
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File filePath = Environment.getExternalStorageDirectory(); //获得sd 卡的路径

StatFs stat = new StatFs(filePath.getPath()); //创建StatFs对象
long blockSize = stat.getBlockSize(); //获取block的size
float totalBlocks = stat.getBlockCount(); //获取block的个数
int sizeInMb = (int) (blockSize * totalBlocks) / 1024 / 1024; //计算总容量
long availableBlocks = stat.getAvailableBlocks(); //可用block的个数
float percent = (int) (blockSize * availableBlocks) / 1024 / 1024; //计算可用容量

notice = notice + " SD卡使用情况: 总容量:" + sizeInMb + "M. 已用:" + (sizeInMb - percent + "M 可用:" + percent + "M.");
return notice;
} else {
notice = notice + " SD卡使用情况:未插入SD卡";
return notice;
}

}
}

以上是关于StorageUtil的主要内容,如果未能解决你的问题,请参考以下文章