android 获取手机SD卡和手机的内部存储

        在开发过程中有时候会获取手机的SD存储使用状况。

布局文件

<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" >

    <TextView
        android:id="@+id/memory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"/>

</LinearLayout>
实现类
package com.example.phonememorystate;

import java.io.File;
import java.text.Format;

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

public class MainActivity extends Activity {
	
	private TextView memoryInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        memoryInfo = (TextView) findViewById(R.id.memory);
        //外部存储的地址
        File SDPath = Environment.getExternalStorageDirectory();
        String SDMemory = getMemoryInfo(SDPath);
        //手机内部存储的地址
        File PhonePath = Environment.getDataDirectory();
        String PhoneMemory = getMemoryInfo(PhonePath);
        memoryInfo.setText("SD卡:" + SDMemory + "\n手机内存:" + PhoneMemory);
        
    }
    
    private String getMemoryInfo(File path){
    	//获取一个磁盘的状态对象
    	StatFs stat = new StatFs(path.getPath());
    	//获得一个扇区的大小
    	long blockSizes = stat.getBlockSize();
    	//获取扇区总数
    	long totalBlocks = stat.getBlockCount();
    	//获得可用扇区数量
    	long availableBlocks = stat.getAvailableBlocks();
    	//获得总空间
    	String totalMemory = Formatter.formatFileSize(this, blockSizes * totalBlocks);
    	//获得可用空间
    	String availableMemory = Formatter.formatFileSize(this, availableBlocks * blockSizes);
    	return "总空间:" + totalMemory + "\n可用空间" + availableMemory;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值