Android监听外部存储设备的状态(SD卡、U盘等等)

jopen 10年前

最近在项目中需要对外部存储设备的状态进行监听,所以整理了此笔记,以便日后查看。

外部存储设备的状态变化时发出的广播

20141217235912078.png

对比不同状态下的广播

1. 插入外部SD卡时:

20141217232924815.png




2. 移除外部SD卡时:

20141217233041972.png





3. 连接PC进入USB大容量存储模式时:

20141217233224574.png





4. 连接PC退出USB大容量存储模式时:

20141217233318144.png




 

代码实现监听

    public void startListen()        {            IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);            intentFilter.setPriority(1000);              intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);            intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);            intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);            intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);             intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);            intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);             intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);            intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);            intentFilter.addAction(Intent.ACTION_MEDIA_NOFS);            intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);            intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);            intentFilter.addDataScheme("file");            registerReceiver(broadcastRec, intentFilter);        }                private final BroadcastReceiver broadcastRec = new BroadcastReceiver() {              @Override              public void onReceive(Context context, Intent intent) {                  String action = intent.getAction();                 Log.d("MediaAction", action);                if (action.equals("android.intent.action.MEDIA_MOUNTED"))                {                      //todo                } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED))                 {                      //todo                }else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)){                }else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)){                }else if (action.equals(Intent.ACTION_MEDIA_SHARED)){                }else {                 }              }          };   

来自:http://blog.csdn.net/giantgreen/article/details/41991291