转自:http://blog.csdn.net/qeqeqe236/article/details/7412929
Android系统提供了Environment 和StatFs两个类,配合可以实现对存储设备容量的查看。
Environment: 获取系统中的存储设备信息
getDataDirectory(): 获取应用存储空间文件对象。
getExternalStorageDirectory(): 获取外部存储设备及SD卡文件对象。
getRootDirectory(): 获取系统空间文件对象。
StatFs: 用于获取具体文件的信息。
getBlockCount(): 获取存储块数量。
getAvailableBlocks(): 获取存储块数量。
getBlockSize(): 获取存储块大小。
因为Android是基于Linux系统的,所以其没有盘符的概念,而且是以存储块来存储数据。所以获得容量的正确方式为:
1. 通过Environment获取需要检测容量的文件对象。
2. 构建StatFs对象。
3. 获取存储块数量。
4. 获取存储块大小。
5. 计算得出容量大小。
通过getBlockSize()方法获取出来的值,是以字节做单位。
下面是代码:
package Getystem_file_info.demo;
import java.io.File;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv1,tv2,tv3,tv4;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findVeiw();
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File externalStoragePath = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStoragePath.getPath());
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getBlockCount();
int availableBlocks = statFs.getAvailableBlocks();
int freeBlocks = statFs.getFreeBlocks();
String[] blockSizes = sizeFormat(blockCount*blockSize);
String[] availableSize = sizeFormat(availableBlocks*blockSize);
String[] freebleSize = sizeFormat(freeBlocks*blockSize);
tv1.setText("外储设备总大小:"+ blockSizes[0] + blockSizes[1] );
tv2.setText("外储设备可用大小:"+ availableSize[0] + availableSize[1] );
tv3.setText("外储设备freeBlocks大小:"+ freebleSize[0] + freebleSize[1] );
}
}
private void findVeiw() {
tv1 = (TextView) this.findViewById(R.id.textview1);
tv2 = (TextView) this.findViewById(R.id.textview2);
tv3 = (TextView) this.findViewById(R.id.textview3);
}
String[] sizeFormat(long size) {
String str = "B";
if(size >= 1024) {
str = "KB";
size /= 1024;
if(size >= 1024) {
str = "MB";
size /= 1024;
}
}
DecimalFormat format = new DecimalFormat();
format.setGroupingSize(3);
String[] result = new String[2];
result[0] = format.format(size);
result[1] = str;
return result;
}
}
获取SDCard 的所存内存,显示出来告诉用户。本篇讲述的内容如下:
- 1、讲述 Environment 类。
- 2、讲述 StatFs 类。
- 3、完整例子读取 SDCard 内存
1、讲述 Environment 类
Environment 是一个提供访问环境变量的类
。
Environment 包含常量:
Environment 常用方法:
2、讲述 StatFs 类
StatFs 一个模拟linux的df命令的一个类,获得SD卡和手机内存的使用情况
StatFs 常用方法:
3、完整例子读取 SDCard 内存
存储卡在 Android 手机上是可以随时插拔的,每次的动作都对引起操作系统进行 ACTION_BROADCAST,本例子将使用上面学到的方法,计算出 SDCard 的剩余容量和总容量。代码如下:
package
com.terry;
import
java.io.File;
import
java.text.DecimalFormat;
import
android.R.integer;
import
android.app.Activity;
import
android.os.Bundle;
import
android.os.Environment;
import
android.os.StatFs;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.ProgressBar;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
getStorageActivity
extends
Activity {
private
Button myButton;
/**
Called when the activity is first created.
*/
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
viewHolder.myButton.setOnClickListener(
new
OnClickListener() {
@Override
public
void
onClick(View arg0) {
//
TODO Auto-generated method stub
getSize();
}
});
}
void
findView(){
viewHolder.myButton
=
(Button)findViewById(R.id.Button01);
viewHolder.myBar
=
(ProgressBar)findViewById(R.id.myProgressBar);
viewHolder.myTextView
=
(TextView)findViewById(R.id.myTextView);
}
void
getSize(){
viewHolder.myTextView.setText(
""
);
viewHolder.myBar.setProgress(
0
);
//
判断是否有插入存储卡
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File path
=
Environment.getExternalStorageDirectory();
//
取得sdcard文件路径
StatFs statfs
=
new
StatFs(path.getPath());
//
获取block的SIZE
long
blocSize
=
statfs.getBlockSize();
//
获取BLOCK数量
long
totalBlocks
=
statfs.getBlockCount();
//
己使用的Block的数量
long
availaBlock
=
statfs.getAvailableBlocks();
String[] total
=
filesize(totalBlocks
*
blocSize);
String[] availale
=
filesize(availaBlock
*
blocSize);
//
设置进度条的最大值
int
maxValue
=
Integer.parseInt(availale[
0
])
*
viewHolder.myBar.getMax()
/
Integer.parseInt(total[
0
]);
viewHolder.myBar.setProgress(maxValue);
String Text
=
"
总共:
"
+
total[
0
]
+
total[
1
]
+
"
\n
"
+
"
可用:
"
+
availale[
0
]
+
availale[
1
];
viewHolder.myTextView.setText(Text);
}
else
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)){
Toast.makeText(getStorageActivity.
this
,
"
没有sdCard
"
,
1000
).show();
}
}
//
返回数组,下标1代表大小,下标2代表单位 KB/MB
String[] filesize(
long
size){
String str
=
""
;
if
(size
>=
1024
){
str
=
"
KB
"
;
size
/=
1024
;
if
(size
>=
1024
){
str
=
"
MB
"
;
size
/=
1024
;
}
}
DecimalFormat formatter
=
new
DecimalFormat();
formatter.setGroupingSize(
3
);
String result[]
=
new
String[
2
];
result[
0
]
=
formatter.format(size);
result[
1
]
=
str;
return
result;
}
}
TIP:要判断手机是否安装了存储卡,可通过 Environment.getExternalStorageState()方法来判断存储卡的状态。
如果你不知道如何创建 SDCard 你可回头看我上篇文章:
点击这里
实例运行效果如图
上篇放了两首歌和一个30多M的音频文件,之前创建时给的500MB空间,现在剩下的刚好。
1. 手机的IMEI
2.手机的制式类型,GSM OR CDMA 手机
3.手机网络国家编码
4.手机网络运营商ID。
5.手机网络运营商名称
6.手机的数据链接类型
7.是否有可用数据链接
8.当前的数据链接类型
9.手机剩余内存
10.手机总内存
11.手机CPU型号
12.手机名称
13.手机型号
14.手机设备制造商名称
上图:
源码如下:
- package com.ransj.tool;
-
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.ObjectInputStream.GetField;
-
- import android.Manifest;
- import android.app.Activity;
- import android.app.ActivityManager;
- import android.app.ActivityManager.MemoryInfo;
- import android.content.Context;
- import android.content.pm.PackageManager;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.Build;
- import android.telephony.TelephonyManager;
- import android.util.Log;
-
- /**
- * retrieve phone info
- *
- *
- */
- public class PhoneInfo {
- private static final String TAG = PhoneInfo.class.getSimpleName();
- private static final String FILE_MEMORY = "/proc/meminfo";
- private static final String FILE_CPU = "/proc/cpuinfo";
- public String mIMEI;
- public int mPhoneType;
- public int mSysVersion;
- public String mNetWorkCountryIso;
- public String mNetWorkOperator;
- public String mNetWorkOperatorName;
- public int mNetWorkType;
- public boolean mIsOnLine;
- public String mConnectTypeName;
- public long mFreeMem;
- public long mTotalMem;
- public String mCupInfo;
- public String mProductName;
- public String mModelName;
- public String mManufacturerName;
-
- /**
- * private constructor
- */
- private PhoneInfo() {
-
- }
-
- /**
- * get imei
- *
- * @return
- */
- public static String getIMEI(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- // check if has the permission
- if (PackageManager.PERMISSION_GRANTED == context.getPackageManager()
- .checkPermission(Manifest.permission.READ_PHONE_STATE,
- context.getPackageName())) {
- return manager.getDeviceId();
- } else {
- return null;
- }
- }
-
- /**
- * get phone type,like :GSM��CDMA��SIP��NONE
- *
- * @param context
- * @return
- */
- public static int getPhoneType(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- return manager.getPhoneType();
- }
-
- /**
- * get phone sys version
- *
- * @return
- */
- public static int getSysVersion() {
- return Build.VERSION.SDK_INT;
- }
-
- /**
- * Returns the ISO country code equivalent of the current registered
- * operator's MCC (Mobile Country Code).
- *
- * @param context
- * @return
- */
- public static String getNetWorkCountryIso(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- return manager.getNetworkCountryIso();
- }
-
- /**
- * Returns the numeric name (MCC+MNC) of current registered operator.may not
- * work on CDMA phone
- *
- * @param context
- * @return
- */
- public static String getNetWorkOperator(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- return manager.getNetworkOperator();
- }
-
- /**
- * Returns the alphabetic name of current registered operator.may not work
- * on CDMA phone
- *
- * @param context
- * @return
- */
- public static String getNetWorkOperatorName(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- return manager.getNetworkOperatorName();
- }
-
- /**
- * get type of current network
- *
- * @param context
- * @return
- */
- public static int getNetworkType(Context context) {
- TelephonyManager manager = (TelephonyManager) context
- .getSystemService(Activity.TELEPHONY_SERVICE);
- return manager.getNetworkType();
- }
-
- /**
- * is webservice aviliable
- *
- * @param context
- * @return
- */
- public static boolean isOnline(Context context) {
- ConnectivityManager manager = (ConnectivityManager) context
- .getSystemService(Activity.CONNECTIVITY_SERVICE);
- NetworkInfo info = manager.getActiveNetworkInfo();
- if (info != null && info.isConnected()) {
- return true;
- }
- return false;
- }
-
- /**
- * get current data connection type name ,like ,Mobile��WIFI��OFFLINE
- *
- * @param context
- * @return
- */
- public static String getConnectTypeName(Context context) {
- if (!isOnline(context)) {
- return "OFFLINE";
- }
- ConnectivityManager manager = (ConnectivityManager) context
- .getSystemService(Activity.CONNECTIVITY_SERVICE);
- NetworkInfo info = manager.getActiveNetworkInfo();
- if (info != null) {
- return info.getTypeName();
- } else {
- return "OFFLINE";
- }
- }
-
- /**
- * get free memory of phone, in M
- *
- * @param context
- * @return
- */
- public static long getFreeMem(Context context) {
- ActivityManager manager = (ActivityManager) context
- .getSystemService(Activity.ACTIVITY_SERVICE);
- MemoryInfo info = new MemoryInfo();
- manager.getMemoryInfo(info);
- long free = info.availMem / 1024 / 1024;
- return free;
- }
-
- /**
- * get total memory of phone , in M
- *
- * @param context
- * @return
- */
- public static long getTotalMem(Context context) {
- try {
- FileReader fr = new FileReader(FILE_MEMORY);
- BufferedReader br = new BufferedReader(fr);
- String text = br.readLine();
- String[] array = text.split("\\s+");
- Log.w(TAG, text);
- return Long.valueOf(array[1]) / 1024;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- public static String getCpuInfo() {
- try {
- FileReader fr = new FileReader(FILE_CPU);
- BufferedReader br = new BufferedReader(fr);
- String text = br.readLine();
- String[] array = text.split(":\\s+", 2);
- for (int i = 0; i < array.length; i++) {
- Log.w(TAG, " ..... " + array[i]);
- }
- Log.w(TAG, text);
- return array[1];
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * get product name of phone
- *
- * @return
- */
- public static String getProductName() {
- return Build.PRODUCT;
- }
-
- /**
- * get model of phone
- *
- * @return
- */
- public static String getModelName() {
- return Build.MODEL;
- }
-
- /**
- * get Manufacturer Name of phone
- *
- * @return
- */
- public static String getManufacturerName() {
- return Build.MANUFACTURER;
- }
-
- public static PhoneInfo getPhoneInfo(Context context) {
- PhoneInfo result = new PhoneInfo();
- result.mIMEI = getIMEI(context);
- result.mPhoneType = getPhoneType(context);
- result.mSysVersion = getSysVersion();
- result.mNetWorkCountryIso = getNetWorkCountryIso(context);
- result.mNetWorkOperator = getNetWorkOperator(context);
- result.mNetWorkOperatorName = getNetWorkOperatorName(context);
- result.mNetWorkType = getNetworkType(context);
- result.mIsOnLine = isOnline(context);
- result.mConnectTypeName = getConnectTypeName(context);
- result.mFreeMem = getFreeMem(context);
- result.mTotalMem = getTotalMem(context);
- result.mCupInfo = getCpuInfo();
- result.mProductName = getProductName();
- result.mModelName = getModelName();
- result.mManufacturerName = getManufacturerName();
- return result;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("IMEI : "+mIMEI+"\n");
- builder.append("mPhoneType : "+mPhoneType+"\n");
- builder.append("mSysVersion : "+mSysVersion+"\n");
- builder.append("mNetWorkCountryIso : "+mNetWorkCountryIso+"\n");
- builder.append("mNetWorkOperator : "+mNetWorkOperator+"\n");
- builder.append("mNetWorkOperatorName : "+mNetWorkOperatorName+"\n");
- builder.append("mNetWorkType : "+mNetWorkType+"\n");
- builder.append("mIsOnLine : "+mIsOnLine+"\n");
- builder.append("mConnectTypeName : "+mConnectTypeName+"\n");
- builder.append("mFreeMem : "+mFreeMem+"M\n");
- builder.append("mTotalMem : "+mTotalMem+"M\n");
- builder.append("mCupInfo : "+mCupInfo+"\n");
- builder.append("mProductName : "+mProductName+"\n");
- builder.append("mModelName : "+mModelName+"\n");
- builder.append("mManufacturerName : "+mManufacturerName+"\n");
- return builder.toString();
- }
-
- }
-
复制代码
注意:需要如下权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>