我在SD卡上打开了一个文件。当有人安装SD卡时,它会导致我的应用程序崩溃。我正在尝试注册ACTION_MEDIA_EJECT广播事件,我收到了,但似乎为时已晚。当我得到它的时候,它已经破坏了我的应用程序。在崩溃我的应用程序之前,有什么方法可以得到通知吗?
添加了一些非常简单的示例代码。当我这样做的时候,当我打开USB(MSC模式)时,它会导致服务崩溃。
测试.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;
}
};
测试服务.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;
}
}