检测SD卡的状态与SD卡的剩余容量

来源:互联网 发布:怎么样求助网络捐款 编辑:程序博客网 时间:2024/06/05 21:49
if(Enviroment.getExternalStoragestate())  状态描述如下:


public void login(View v){

        String name = et_name.getText().toString();
        String pass = et_pass.getText().toString();

        CheckBox cb = (CheckBox) findViewById(R.id.cb);
        //判断选框是否被勾选
        if(cb.isChecked()){
            //MEDIA_UNKNOWN:不能识别sd卡
            //MEDIA_REMOVED:没有sd卡
            //MEDIA_UNMOUNTED:sd卡存在但是没有挂载
            //MEDIA_CHECKING:sd卡正在准备
            //MEDIA_MOUNTED:sd卡已经挂载,可用
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

                //返回一个File对象,其路径是sd卡的真实路径
                File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
    //            File file = new File("sdcard/info.txt");
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(file);
                    fos.write((name + "##" + pass).getBytes());
                    fos.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else{
                Toast.makeText(this, "sd卡不可用哟亲么么哒", 0).show();
            }
        }

        //创建并显示吐司对话框
        Toast.makeText(this, "登录成功", 0).show();
    }

}

----------------------------------------------------------------------------------

我是分割线

public class MainActivity extends Activity {

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

     //查询手机的区块大小和区块的数量
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize;
        long totalBlocks;
        long availableBlocks;

        //获取当前系统版本的等级 ,这个方法写如果大于4.3就用LONG,否则就用旧版本
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
            //一万个注意,在原有的方法加long是4.3版本以上的新方法,在4.3及以下运行,不报错,但是运行直接崩溃
             blockSize = stat.getBlockSizeLong();
             totalBlocks = stat.getBlockCountLong();
             availableBlocks = stat.getAvailableBlocksLong();
        }
        else{
            blockSize = stat.getBlockSize();
            totalBlocks = stat.getBlockCount();
            availableBlocks = stat.getAvailableBlocks();
        }
      
        TextView tv = (TextView) findViewById(R.id.tv);
        //这里表示我们将得到的一个内存大小数字做了一个转换,formatSize会报错,因为这不是android API里面的方法,创建formaSize方法
        tv.setText(formatSize(availableBlocks * blockSize));
    }

    private String formatSize(long size) {
        return Formatter.formatFileSize(this, size);
    }

}






0 0