我通过下一个方式写信给文件:
long byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = zipStream.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
byteCount += bytesRead;
// ...
if (fOut != null) {
fOut.flush();
fOut.close();
}
if (zipStream != null) {
zipStream.close();
}
} catch (Exception e) {...}
当我在下载系统时取消我的SD卡时,系统会在几秒钟内终止我的申请流程。据我所知,这是因为系统需要清除SD卡卸载后仍然存活的资源。在这种情况下如何避免杀死我的申请?
我抓到的一切:
W/System.err(2732): java.io.IOException: I/O error
06-06 16:25:01.411: W/System.err(2732): at org.apache.harmony.luni.platform.OSFileSystem.write(Native Method)
06-06 16:25:01.411: W/System.err(2732): at dalvik.system.BlockGuard$WrappedFileSystem.write(BlockGuard.java:171)
06-06 16:25:01.411: W/System.err(2732):
答案 0 :(得分:2)
您可以在卸载SD卡时收听媒体状态更改并完成活动或停止写入过程。
以下应该开始:
private BroadcastReceiver mStorageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == Intent.ACTION_MEDIA_REMOVED ||
action == Intent.ACTION_MEDIA_BAD_REMOVAL ||
action == Intent.ACTION_MEDIA_EJECT ||
action == Intent.ACTION_MEDIA_NOFS ||
action == Intent.ACTION_MEDIA_SHARED ||
action == Intent.ACTION_MEDIA_UNMOUNTED) {
finish();
}
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_NOFS);
filter.addAction(Intent.ACTION_MEDIA_SHARED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
registerReceiver(mStorageReceiver, filter);
}
请检查Intent API docs以了解其他与媒体相关的操作。此外,当您完成活动/流程时,请不要忘记取消注册mStorageReceiver
。