Android -- (静态广播) APP 监听U盘挂载
Android – (静态广播) APP 监听U盘挂载
-
注册广播(AndroidManifest.xml):
<receiver android:name=".receiver.MountReceiver"> <intent-filter> <action android:name="android.intent.action.MEDIA_MOUNTED" /> <action android:name="android.intent.action.MEDIA_UNMOUNTED" /> <action android:name="android.intent.action.MEDIA_REMOVED" /> <action android:name="android.intent.action.MEDIA_EJECT" /> <data android:scheme="file" /> </intent-filter> </receiver>
-
自定义广播类:
/** * U盘挂载事件 * EJECT/REMOVE/MOUNT/UNMOUNT */ public class MountReceiver extends BroadcastReceiver { private static final String TAG = "MountReceiver"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (TextUtils.isEmpty(action)) return; if (intent.getData() == null) return; try { String path = intent.getData().getPath(); Log.i(TAG, "usb path: " + path); if (path.contains("emulated")) {//防止自启时本地路径触发 return; } //在后台服务里去执行具体处理逻辑 context.startService(CoreService.getIntent(context, action, path)); } catch (Throwable e) { e.printStackTrace(); } } }