我有一个正在运行的应用程序服务。当用户返回应用程序时,我检查服务是否正在运行,如果确实如此,我尝试连接此服务并显示包含一些数据的片段。但有时我会犯这个错误:
Fatal Exception: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.fjuul.fjuul.MainActivity.showGPSFragment(MainActivity.java:712)
尝试连接servise
private void connectService() {
registerFitnessReceiver();
sConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (service != null) {
callGPSFragment(status, mapWaySelections, activityType);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
Intent requestIntent = new Intent(MainActivity.this, FitnessRecordingService.class);
requestIntent.setAction(FitnessRecordingService.GET_FITNESS_RECORD_ACTION);
bindService(requestIntent, sConn, 0);
}
如果连接完成 - 创建片段并填充数据
private void callGPSFragment() {
...
GPSServicePresenter gpsServicePresenter = new GPSServicePresenter();
showGPSFragment(gpsServicePresenter);
调用片段
public void showGPSFragment(GPSServicePresenter gpsServicePresenter) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.body_fragent, gpsServicePresenter);
Fragment oldFragment = fragmentManager.findFragmentByTag(SplashFragment.tag());
if (oldFragment != null) {
transaction.remove(oldFragment);
}
transaction.commitAllowingStateLoss();
}
答案 0 :(得分:2)
问题是与服务的连接是异步发生的,并且在活动被销毁后有可能会调用onServiceConnected(ComponentName, IBinder)
。
为了解决此问题,您可以使用Activity.isDestroyed()
功能(和/或isFinishing()
,如果您想支持旧版Android)来检查您的活动状态并阻止其后的互动#39;被摧毁了:
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (service != null && !isDestroyed()) {
callGPSFragment(status, mapWaySelections, activityType);
}
}