您的位置:首页 > 其它

安卓中查看SD卡剩余空间

2016-08-05 19:36 197 查看
在我们向SD卡中传入视频等较大容量的文件时,先要对SD卡剩余容量进行获取,然后与要传文件大小进行比较。

多的不说,直接看代码:

 MainActivity类:

 import java.io.File;

import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.text.format.Formatter;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView text1;
private TextView text2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.save_space);
text2 = (TextView) findViewById(R.id.totle_space);
File file = Environment.getExternalStorageDirectory();
//StatFs是一个模拟linux系统的df命令的类,用于获取SD卡和手机内存的使用情况
StatFs stat = new StatFs(file.getPath());
//所有存储设备都会被分成若干个区块,每个区块的内存大小相同
//存储设备的总大小=所有区块数*内个区块所占内存大小。
//获取每个区块所占内存大小
long blocksize = stat.getBlockSize();
//获取总的区块数量
long totleblockcount = stat.getBlockCount();
//获取可用的区块总数量
long availableblocks = stat.getAvailableBlocks();
text1.setText(formateSize(blocksize*availableblocks));
text2.setText(formateSize(blocksize*totleblockcount));
}
//将字节数格式转化(根据实际情况转化为MB、KB、TB等)
public String formateSize(long size){
return Formatter.formatFileSize(this, size);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SD卡剩余空间:" />
<TextView
android:id="@+id/save_space"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SD卡总空间:" />
<TextView
android:id="@+id/totle_space"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</LinearLayout>

效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: