我在SD卡上打开了一个文件。当有人安装SD卡时,它会崩溃我的应用程序。我正在尝试注册ACTION_MEDIA_EJECT广播事件,我收到了,但似乎我得到的太迟了。当我得到它时,它已经崩溃了我的应用程序。在崩溃我的应用程序之前有没有办法得到通知?
添加了一些非常简单的示例代码。当我这样做时,当我打开USB(MSC模式)时,它会崩溃服务。
Test.java
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
startService(new Intent(this, TestService.class));
bindService(new Intent(this, TestService.class), serviceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
}
protected TestService testService;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
TestService.LocalBinder binder = (TestService.LocalBinder) service;
testService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
testService = null;
}
};
TestService.java
@Override
public void onCreate() {
super.onCreate();
try {
mFileOutputStream = new FileOutputStream("/sdcard/test2", true);
} catch (Exception e) {
}
}
@Override
public IBinder onBind(Intent intent) { return binder; }
public static class LocalBinder extends Binder {
public static TestService getService() {
return _this;
}
}
答案 0 :(得分:7)
它正在杀死你的应用程序,因为它是android中一个文档化的设计决定,当需要从设备卸载sdcard时杀死任何持有sdcard打开句柄的进程(例如,将USB挂载到连接的PC) 。
仍然具有打开文件句柄的文件系统无法完全卸载。在操作系统级别,没有办法撤销文件句柄,没有杀死它被授予的进程,所以这就是android最终做的。
答案 1 :(得分:2)
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//access external file
}
如果不了解更多关于抛出异常的内容,这就是我所能推荐的全部内容。
此外,Environment类文档中的以下代码可能有所帮助:
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);
}