2

我通过以下方式写入文件:

        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): 
4

1 回答 1

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 文档以了解其他与媒体相关的操作。mStorageReceiver此外,当您完成活动/流程时,不要忘记取消注册。

于 2013-06-06T17:00:02.477 回答