Android MVP-处理onActivityResult的正确方法是什么?

时间:2019-01-07 11:17:19

标签: android android-lifecycle onactivityresult android-mvp

onActivityResult应该委托给Presenter。然后Presenter应该决定如何处理结果。问题是如何以干净的方式进行操作?

Google示例中有一个示例应用程序: https://github.com/googlesamples/android-architecture/blob/todo-mvp-dagger/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksFragment.java#L115-L118

它将结果委托给Presenter

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    mPresenter.result(requestCode, resultCode);
}

但是此解决方案中存在一个 bug Presenter使用View方法删除Fragment(在这种情况下为onDestroy()):

@Override
public void onDestroy() {
    super.onDestroy();
    mPresenter.dropView();  
}

并采用View方法中的onResume()

@Override
public void onResume() {
    super.onResume();
    mPresenter.takeView(this);
}

当我们为结果打开新活动时。然后旋转电话,然后完成当前活动并返回第一个活动,Presenter将没有View,因为onActivityResult将在onResume之前被调用。 / p>

D/TasksFragment: onCreate
D/TasksFragment: onCreateView
D/TasksFragment: onStart
D/TasksFragment: onResume
--- open new activity for the result ---
D/TasksFragment: onPause
D/TasksFragment: onStop
--- rotate the phone ---
--- finish current activity ---
D/TasksFragment: onDestroy
D/TasksFragment: onCreate
D/TasksFragment: onCreateView
D/TasksFragment: onStart
D/TasksFragment: onActivityResult (called before onResume)
D/TasksFragment: onResume

0 个答案:

没有答案