---
title: "androidU盘检测"
author: "流沙-只如初见"
date: "2012-08-18T09:19:54Z"
tags: []
categories: ["移动开发"]
slug: "androidu"
draft: false
lastmod: "2012-08-18T09:19:54Z"
id: 1636323
url: "https://ouclbc.iteye.com/blog/1636323"
---

在网上查了一些资料。U盘检测的方法一般有两种方式，检测电池或者查看配置信息。
1.Batterymanager检测方法如下：
IntentFilter mIntentFilter = new IntentFilter(); 
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); 
registerReceiver(BtStatusReceiver, mIntentFilter);
 
public BroadcastReceiver BtStatusReceiver = new BroadcastReceiver() // receive broadcast that BT Adapter status change
 {
    @Override
    public void onReceive(Context context, Intent intent)
    {
     String action = intent.getAction();
     if (action.equals(Intent.ACTION_BATTERY_CHANGED))
     {       
      Log.d("Battery", "" + intent.getIntExtra("plugged", 0));Toast text=Toast.makeText(context, "ACTION_USB_DEVICE_ATTACHED"+intent.getIntExtra("plugged", 0), Toast.LENGTH_LONG);
         text.show();
         dataview.setText(""+intent.getIntExtra("plugged", 0));
     }
    }      
 };
intent.getIntExtra("plugged", 0)得到的值分别为：
0)：断开
1)：连上USB
2)：连上了充电器

2检测listroot是否有文件路径多出
public class testU implements Runnable{
    private File roots=File.listRoots();
    public testU() {
    }
    
    public void run() {
        System.out.println("检测系统开启...");
        while (true) {
            File tempFile = File.listRoots();
            boolean sign = false;
            if (tempFile.length > roots.length) {
                for (int i = tempFile.length - 1; i >= 0; i--) {
                    sign = false;
                    for(int j = roots.length - 1; j >= 0; j--) {
                        if (tempFile*.equals(roots)) {
                            sign = true;
                        }
                    }
                    if (sign == false) {
                        System.out.println("插入盘符:"+tempFile*.toString());
                    }
                }
                roots=File.listRoots();//更新roots
            } else {
                for (int i = roots.length - 1; i >= 0; i--) {
                    sign = false;
                    for(int j = tempFile.length - 1; j >= 0; j--) {
                        if (tempFile.equals(roots*)) {
                            sign = true;
                        }
                    }
                    if (sign == false) {
                        System.out.println("退出盘符:"+roots*.toString());
                    }
                }
                roots=File.listRoots();//更新roots
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(testU.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args) {
        new Thread(new testU()).start();
    }
}
检测u盘插入后，获取u盘总内存及可利用内存可以采用statFs获取。类似SD卡。
final StatFs stat = new StatFs(Udisk.getPath());
final long blockSize = stat.getBlockSize();
final long totalBlocks = stat.getBlockCount();
final long availableBlocks = stat.getAvailableBlocks();
    long mTotalSize = totalBlocks * blockSize;
long mAvailSize = availableBlocks * blockSize;
3，检测配置文件
File Usbfile = new File("/proc/partitions");
                if(Usbfile.exists()){
                	 try {
                     	FileReader  file= new FileReader("/proc/partitions");
                         BufferedReader br=new BufferedReader(file);
                         String strLine="";
                         while((strLine=br.readLine())!=null)
                        {
                             if(strLine.indexOf("sd")>0)
                            {
                            	 searchFile("usb",Ufile);
                                 System.out.println("Udisk insert---------------------------------->");
                                 Log.d("Udisk","Udisk insert---------->");
                                 break;
                             }
                         }
                         br.close();
                         file.close();
                     } catch (Exception e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                }   
然后获取usb路径
//获usb文件路径
    private void searchFile(String keyword,File filepath)  
    {
    	System.out.println("searchFile start...");
    	File files = filepath.listFiles();      
            if (files.length > 0)  
            {  
                    for (File file : files)  
                    {  
                     if (file.isDirectory())  
                     {  
                      //如果目录可读就执行（一定要加，不然会挂掉）  
                      if(file.canRead()){  
                       searchFile(keyword,file);  //如果是目录，递归查找  
                      }  
        }  
                     else {    
                       //判断是文件，则进行文件名判断
                    	 //System.out.println("*******************"+file.getName().indexOf(keyword));
                                try {     
                                 if (file.getName().indexOf(keyword) > -1||file.getName().indexOf(keyword.toUpperCase()) > -1)   
                                 {
                                	 System.out.println("Udisk find:------------------------------>");
                                	 System.out.println(file.getPath());
                                	 System.out.println(file.getName());
                                	 Log.d("Udisk",file.getName());
                                 }     
                               } catch(Exception e) {     
                                        Toast.makeText(this,"find error", Toast.LENGTH_SHORT).show();     
                                }     
                       }  
                    }  
         }   
    }