在Android MVP中使用Dagger实现GoogleApiClient?

10

我有几个问题,

首先,当我阅读一些文章时,我应该在活动中实现LocationListener,ConnectionCallback和OnConnectionFailedListener接口,

将这些类的实现分别放在不同的文件中是正确的吗?

像下面这样:

public class LocationListener implements 
           com.google.android.gms.location.LocationListener {
@Inject
Location mLastLocation;
@Override
public void onLocationChanged(Location location) {
    // Assign the new location
    mLastLocation = location;
    // Displaying the new location on UI
 }
}

在我的活动中,我处理显示mLastLocation属性是正确的吗?

//Fields
@Inject
GoogleApiClient client;
Location mLastLocation;
//Fields
  mLastLocation = LocationServices.FusedLocationApi.getLastLocation(client);

其次,我该如何编写它的提供者方法?我的猜测是这样的,你们有什么建议吗?

//Constructor
public LocationModule(Context context, GoogleApiClient.ConnectionCallbacks callback, GoogleApiClient.OnConnectionFailedListener listener) {
    this.context = context;
    this.callback = callback;
    this.listener = listener;
}
@Provides
@Singleton
GoogleApiClient providesGoogleApi() {
    return new GoogleApiClient.Builder(context)
            .addOnConnectionFailedListener(listener)
            .addConnectionCallbacks(callback)
            .addApi(LocationServices.API)
            .build();
}

最后,在 Android 6 及以上设备上处理权限应该放在哪儿?是在 View 上还是 Presenter 上?

我听说 View 很蠢,所以不需要测试它,但我该如何遵循这个原则呢?

如果有人能给我一个符合我的情况的参考或 Github 的示例代码,那就太好了。

1个回答

5
首先,您可以将MVP视图层视为纯Android模块,这意味着与Android操作系统的任何通信(如请求权限)都必须使用此层处理,并将结果返回给Presenter,由Presenter决定下一步该做什么。
关于分离这些类的实现,我个人喜欢分离类以获得更清晰的可视化效果,当我正在查找某个类的代码时。我认为没有人能建议最佳实践,因为它取决于您的模块和实现。根据《Clean Code》书籍,在这种决策情况下,您需要更多地考虑代码的可读性。
最后,关于LocationModule,它完全正确,但如果我是您,我甚至会在更高级别的组件(例如ApplicationComponent)中请求Context,并从LocationModule构造函数中删除它。
//Constructor
public LocationModule(GoogleApiClient.ConnectionCallbacks callback, GoogleApiClient.OnConnectionFailedListener listener) {
    this.callback = callback;
    this.listener = listener;
}

@Provides
@Singleton
GoogleApiClient providesGoogleApi(Context context) {
    return new GoogleApiClient.Builder(context)
            .addOnConnectionFailedListener(listener)
            .addConnectionCallbacks(callback)
            .addApi(LocationServices.API)
            .build();
}

在较高的模块中,可以使用相关提供程序提供上下文。

以下是一个示例仓库,可以在这方面帮助您:

https://github.com/mmirhoseini/fyber_mobile_offers


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