2016-09-19 36 views
0

我正在开发一个Android应用程序,并希望使用Dagger作为我的DI框架。但我不知道如何注入使用回调的依赖关系。如何使用依赖注入与java回调

比如我想要得到的位置,我用GoogleApiClient此:

public class LocationProvider implements ILocationProvider, 
            GoogleApiClient.ConnectionCallbacks, 
            GoogleApiClient.OnConnectionFailedListener { 
    private GoogleApiClient googleApiClient; 
    private ILocationRequester requester; 

    public LocationProvider(@NonNull Context context, @NonNull ILocationRequester requester) { 
     this.requester = requester; 

     googleApiClient = new GoogleApiClient.Builder(context) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    } 

    @Override 
    public void beginGetLocation() { 
     googleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
     requester.locationFound(lastLocation); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     requester.locationFound(null); 
    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
     requester.locationFound(null); 
    } 
} 

在这种情况下,我想用匕首可以嘲笑它在我的测试中注入GoogleApiClient例如,但因为它取决于这个班级,我不能。该场景对于任何使用回调的长时间运行操作都是有效的,即使我使用其他类来实现回调。

有没有人知道这个解决方案?

回答

0

您需要为接口编写一个实现类让我们称之为“ILocationRequesterImpl”,然后编写一个方法来提供该impl的一个实例。例如你的模块中:

@Provides 
public ILocationRequester provideLocationRequester() { 
    ILocationRequesterImpl lr=new ILocationRequesterImpl(); 
    return lr; 
} 

另一种方法是使用构造函数注入在ILocationRequesterImpl类象下面这样:

public class ILocationRequesterImpl implements ILocationRequester { 
@Inject 
public ILocationRequesterImpl() { 
} ... ... 

,然后这时候你的模块中简单地写:

@Provides 
public ILocationRequester provideLocationRequester(ILocationRequesterImpl lr) { 
    return lr; 
}