preventing a crash when someone mounts an Android SD card

你离开我真会死。 提交于 2019-12-04 11:11:46

It is killing your application because it is a documented design decision in android to kill any process holding an open handle to the sdcard when the sdcard needs to be unmounted from the device (for example to be USB mounted to a connected PC).

A file system which still has open file handles cannot be cleanly unmounted. At the operating system level, there's no way to revoke a file handle, short of killing the process to which it was granted, so that is what android ultimately does.

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    //access external file
}

Without knowing more about what exceptions are being thrown, this is about all I can recommend.

Also, the following code from the Environment class documentation may help:

BroadcastReceiver mExternalStorageReceiver;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;

void updateExternalStorageState() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
    handleExternalStorageState(mExternalStorageAvailable,
            mExternalStorageWriteable);
}

void startWatchingExternalStorage() {
    mExternalStorageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("test", "Storage: " + intent.getData());
            updateExternalStorageState();
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    registerReceiver(mExternalStorageReceiver, filter);
    updateExternalStorageState();
}

void stopWatchingExternalStorage() {
    unregisterReceiver(mExternalStorageReceiver);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!