美文网首页
android获取手机存储状态

android获取手机存储状态

作者: Jay_Chan | 来源:发表于2017-08-09 12:35 被阅读0次

布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

MainActivity代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvState = (TextView) findViewById(R.id.tv_state);

        //获得sd卡的内存状态
        File sdCardDir = Environment.getExternalStorageDirectory() ;
        String sd = getMemoryInfo(sdCardDir) ;

        //获得手机内部的存储状态
        File dataDir = Environment.getDataDirectory() ;
        String phone = getMemoryInfo(dataDir) ;

        tvState.setText("SD卡: \n"+sd+"\n\n手机内部: \n"+phone);
    }


    private String getMemoryInfo(File path) {

        //获得一个磁盘状态对象
        StatFs stat  = new StatFs(path.getPath()) ;
        long blockSize = stat.getBlockSize() ;   //获得一个扇区的大小
        long totalBlocks = stat.getBlockCount() ;   //获得扇区的数量
        long availableBlocks = stat.getAvailableBlocks() ;   //获得可用扇区的数量

        //总空间
        String totalMemory = Formatter.formatFileSize(this,blockSize* totalBlocks) ;

        //可用空间
        String availableMemory = Formatter.formatFileSize(this, blockSize*availableBlocks) ;

        return "总空间: "+totalMemory+"\n"+"可用空间: "+availableMemory;
    }
}

效果图

由于测试的手机没有sdCard,所以显示sdCard的总空间和可用空间和手机内部存储的一致,若手机有sdCard就会根据sdCard的总空间和可用空间来显示了。

相关文章

网友评论

      本文标题:android获取手机存储状态

      本文链接:https://www.haomeiwen.com/subject/mmwfrxtx.html