安卓系统内存检测--StatFsProgressBar:自定义view

先上图:

-安卓系统内存检测--StatFsProgressBar:自定义view_第1张图片-

项目要求在很多界面中展示最底部的内存状态:占用空间,可用空间大小;考虑多界面复用,我自定义view

首先绘制布局、

[java] view plain copy
  
  
  
      
  
      
  
          
          
  
      
  
  
自定义view方法:主要通过statFs 方法获取总扇区大小以及剩余扇区大小然后求比,把值赋给progressbar

/** 
 * 类名称: 
 * 作者: aj 
 * 时间: 2017/11/8 下午6:32 
 * 功能: 
 */  
  
public class MemoryProgressBarView extends RelativeLayout {  
  
    private TextView tvAlready, tvUnused;  
    private final ProgressBar progressBar;  
  
    public MemoryProgressBarView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
  
        // 加载布局  
        View inflate = LayoutInflater.from(context).inflate(R.layout.view_memory, this);  
        // 获取控件  
        tvAlready = (TextView) findViewById(R.id.tv_already);  
        tvUnused = (TextView) findViewById(R.id.tv_unused);  
        progressBar = (ProgressBar) findViewById(R.id.download_progressBar);  
        progressBar.setMax(100);  
  
    }  
  
    public void initProgressBar(Context context) {  
  
        //获得sd卡的内存状态  
        File sdcardFileDir = Environment.getExternalStorageDirectory();  
        String sdcardMemory = getMemoryInfo(sdcardFileDir, context);  
        //获得手机内部存储控件的状态  
        File dataFileDir = Environment.getDataDirectory();  
        String dataMemory = getMemoryInfo(dataFileDir, context);  
  
//        tvAlready.setText("SD卡: " + sdcardMemory + "\n手机内部: " + dataMemory);  
        tvAlready.setText("手机内部: " + dataMemory);  
  
  
    }  
  
    /** 
     * 根据路径获取内存状态 
     * 
     * @param path 
     * @return 
     */  
    @SuppressWarnings("deprecation")  
    private String getMemoryInfo(File path, Context context) {  
        //获得一个磁盘状态对象  
        StatFs stat = new StatFs(path.getPath());  
  
        //获得一个扇区的大小  
        long blockSize = stat.getBlockSize();  
  
        //获得扇区的总数  
        long totalBlocks = stat.getBlockCount();  
  
        //获得可用的扇区数量  
        long availableBlocks = stat.getAvailableBlocks();  
  
        //获得已用的扇区数量  
        long alreadyBlocks = totalBlocks - availableBlocks;  
  
        //设置进度条  
        long l = (((alreadyBlocks * 100) / totalBlocks));  
        progressBar.setProgress((int) (l));  
  
  
        //总空间  
//        String totalMemory = Formatter.formatFileSize(context, totalBlocks * blockSize);  
  
        //占用空间  
        String alreadyMemory = Formatter.formatFileSize(context, alreadyBlocks * blockSize);  
  
        //可用空间  
        String availableMemory = Formatter.formatFileSize(context, availableBlocks * blockSize);  
  
        return "占用空间:" + alreadyMemory + "   可用空间:" + availableMemory;  
    }  
  
} 

运用:在页面布局引入自定义的view

        


调用方法:

 memoryView = (MemoryProgressBarView) findViewById(R.id.memory_progress);
        memoryView.initProgressBar(context);
最终实现上图效果 实现上图效果

你可能感兴趣的:(移动开发)