在使用MVP模式开发Android应用时,应该将Android服务调用和对GoogleAPIClient的调用写在哪里?

11
我正在尝试参考此链接:https://github.com/jpotts18/android-mvp,在我的Android项目中实现MVP模式。我已经成功地实现了view/presenter/interactor类,但不确定如何处理以下问题:
1. 在哪里放置service调用代码? 无法在presenter或interactor类中获取上下文,因此无法在那里放置service调用代码。
2. 在哪里实现GoogleApiClient类? 由于GoogleApiClient运行需要上下文,所以也无法在presenter或interactor中实现。
2个回答

7
使用dagger可以更轻松地在Presenter中注入Interactor。请尝试访问此链接(https://github.com/spengilley/AndroidMVPService)。
我正在尝试不使用dagger来实现这个目标,但这似乎违反了MVP架构。
从Activity中,我创建了一个Interactor实例。然后创建一个Presenter实例,其中包括Interactor作为其中的一个参数。 Activity
public class SomeActivity extends Activity implements SomeView {
   private SomePresenter presenter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      SomeInteractor interactor = new SomeInteractorImpl(SomeActivity.this);
      presenter = new SomePresenterImpl(interactor,this);
   }

   @Override
   protected void onStart() {
     super.onStart();
     presenter.startServiceFunction();
   }

Presenter

public interface SomePresenter {
   public void startServiceFunction();
}

演示文稿实现
public class SomePresenterImpl implements SomePresenter {
   private SomeInteractor interactor;
   private SomeView view;
   public SomePresenterImpl(SomeInteractor interactor,SomeView view){
      this.interactor = interactor;
      this.view = view;
   }
   @Override
   public void startServiceFunction() {
      interactor.startServiceFunction();
   }
}

交互器

public interface SomeInteractor {
   public void startServiceFunction();
}

执行者实现

public class SomeInteractorImpl implements SomeInteractor {
   private Context context;

   public SomeInteractorImpl(Context context) {
      this.context = context;
   }

   @Override
   public void startServiceFunction() {
      Intent intent = new Intent(context, SomeService.class);
      context.startService(intent);
   }
}

3
我认为这个答案不正确。如果您遵循《Clean Architecture》中的准则[链接],交互器(interactor)不应了解任何特定的框架,而且应该是Android不可知的。因此,它应该完全摆脱任何与Android相关的内容,包括Context类。 - koufa
@koufa你需要将Context放在某个地方。否则,你如何与Service交互?你有什么建议? - AutonomousApps
2
如果将应用程序分层,则交互器将驻留在域层中。该层不应具有任何特定于框架的依赖项,即没有 Android 依赖项。Service 的初始化应该放在 DataLayer 中,在其中将这段代码Intent intent = new Intent(context, SomeService.class);context.startService(intent); 装入实现来自域层的接口的类中。然后,交互器仅会知道此接口而不知道其具体实现。 - koufa

0

我也在寻找你的第一个问题的答案。不过,我有第二个问题的答案。

答案是Dagger2。(http://google.github.io/dagger/)你可以通过使用Dagger2轻松注入GoogleApiClient对象。


7
当使用依赖注入(DI)时,你如何处理回调GoogleApiClient.ConnectionCallbacksGoogleApiClient.OnConnectionFailedListener?举个例子会更有帮助。 - sidecarcat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接