Android 检测是否挂载U盘的代码
时间: 2024-02-20 16:58:53 浏览: 127
在 Android 上检测 U 盘是否挂载需要使用 USB 设备管理器。以下是一个检测 U 盘是否挂载的示例代码:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 创建一个 BroadcastReceiver,用于监听 U 盘插拔事件:
```java
public class USBReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
// U 盘已插入
Toast.makeText(context, "USB device attached", Toast.LENGTH_SHORT).show();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// U 盘已卸载
Toast.makeText(context, "USB device detached", Toast.LENGTH_SHORT).show();
}
}
}
```
3. 在 Activity 中注册 BroadcastReceiver:
```java
public class MainActivity extends AppCompatActivity {
private USBReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
mReceiver = new USBReceiver();
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
```
该代码会注册一个 BroadcastReceiver,用于监听 U 盘插拔事件。如果 U 盘被插入,将会弹出一个 Toast 提示“USB device attached”;如果 U 盘被卸载,将会弹出一个 Toast 提示“USB device detached”。请注意,该代码需要在 Android 3.1 及以上版本中运行。
阅读全文