android如何在拔出USB时及时清除读取的数据缓存,清除缓存的方法实现
时间: 2023-05-25 18:03:12 浏览: 202
Android在拔出USB时会触发`ACTION_UMS_DISCONNECTED`广播,可以在接收到此广播时清除读取的数据缓存。
清除缓存的方法实现如下:
```java
// 清除缓存方法
public void clearCache() {
FileInputStream fis = null;
try {
fis = this.openFileInput("data.txt");
if (fis != null) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fis.read(buffer)) != -1) {
// 清除缓存
Arrays.fill(buffer, (byte) 0);
}
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 注册广播接收器
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_UMS_DISCONNECTED);
registerReceiver(mUsbDisconnectedReceiver, filter);
}
// 广播接收器
private BroadcastReceiver mUsbDisconnectedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_UMS_DISCONNECTED)) {
// 拔出USB时清除缓存
clearCache();
}
}
};
// 注销广播接收器
private void unregisterReceiver() {
unregisterReceiver(mUsbDisconnectedReceiver);
}
```
在`clearCache()`方法中,先打开文件输入流`FileInputStream`,然后读取数据缓存并清空。在广播接收器中,接收到`ACTION_UMS_DISCONNECTED`广播后即执行`clearCache()`方法清除读取的数据缓存。
需要注意的是,在使用文件输入流`FileInputStream`时,一定要在读取完成后关闭该输入流,避免造成资源浪费。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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://csdnimg.cn/download_wenku/file_type_ask_c1.png)