android 监听u盘拔插事件
时间: 2023-12-12 08:01:04 浏览: 230
在Android平台上,可以通过注册广播接收器来监听U盘的插拔事件。具体步骤如下:
1. 首先,在AndroidManifest.xml文件中为应用程序添加下面的权限声明:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2. 创建一个广播接收器类,继承自BroadcastReceiver,并重写onReceive()方法。如下所示:
```java
public class USBReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
// U盘插入事件,在此处理相关逻辑
Toast.makeText(context, "U盘已插入", Toast.LENGTH_SHORT).show();
} else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
// U盘拔出事件,在此处理相关逻辑
Toast.makeText(context, "U盘已拔出", Toast.LENGTH_SHORT).show();
}
}
}
}
```
3. 在应用程序的Activity中注册广播接收器。如下所示:
```java
public class MainActivity extends AppCompatActivity {
private USBReceiver usbReceiver;
private IntentFilter usbIntentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbReceiver = new USBReceiver();
usbIntentFilter = new IntentFilter();
usbIntentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
usbIntentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(usbReceiver, usbIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(usbReceiver);
}
}
```
通过以上步骤,我们就可以在应用程序中监听U盘的插拔事件了。当U盘插入时,会弹出一个"U盘已插入"的Toast提示;当U盘拔出时,会弹出一个"U盘已拔出"的Toast提示。你也可以根据需求,在对应的事件处理逻辑中执行其他操作。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)