android監聽SD卡掛載並獲取路徑

yingxian_Fei發表於2016-04-27

android的app開發或者framework開發中可以通過監聽媒體掛載廣播獲取sd卡的拔插狀態並獲取到當前狀態變化的儲存裝置資訊。


1、測試程式碼

public class LSLogHandler  {
        private Context mContext;

	public LSLogHandler(Context context) {
		mContext = context;
		final IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		filter.addDataScheme("file");
		mContext.registerReceiver(mLogReceiver, filter);
	}

	private final BroadcastReceiver mLogReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {			                       
                        Log.d(TAG, "BroadcastReceiver onReceive.");
			String action = intent.getAction();
                        Log.d(TAG, "Receive " + action);
                        if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
                            StorageVolume volume = (StorageVolume) intent.getParcelableExtra(StorageVolume.EXTRA_STORAGE_VOLUME);
                            final String volumePath = null == volume ? "" : volume.getPath();Log.d(TAG, "volume=" + volumePath);
                        }
                 }
         };
}


2、知識點

(1)、媒體掛載廣播;

(2)、需要新增DataScheme,否則同樣監聽不到廣播;

相關文章