Android 監聽外部U盤插入事件
阿新 • • 發佈:2021-09-29
1、在AndroidManifest.xml 加入讀取外部儲存器許可權
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2、註冊動態廣播
public static void register(Context context){ IntentFilter filter = null; filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_MOUNTED);//接收U盤掛載廣播 filter.addAction(Intent.ACTION_MEDIA_REMOVED); //接收U盤解除安裝廣播 filter.addDataScheme("file"); context.registerReceiver(mSdcardReceiver, filter,"android.permission.READ_EXTERNAL_STORAGE",null); } static BroadcastReceiver mSdcardReceiver = new BroadcastReceiver(){ @Overridepublic void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)){ Toast.makeText(context, "path:"+intent.getData().getPath(), Toast.LENGTH_SHORT).show(); }else if(intent.getAction().equals(Intent.ACTION_MEDIA_REMOVED)){ Log.i("ants", "remove ACTION_MEDIA_REMOVED"); } } };