在Android Java中传递上下文是不好的,但如何访问服务中的活动?
我知道传递静态上下文是不允许的,应该避免。我理解背后的原因
我的问题是,我们如何访问某些需要在其参数中“活动”的调用。例如:
public class BackgroundServiceParent extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.CONFIG_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.useDefaultAccount()
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
....
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
(Activity) applicationContext, 0).show();
return;
}
if (!authInProgress) {
try {
authInProgress = true;
result.startResolutionForResult((Activity) applicationContext, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG,
Exception while starting resolution activity", e);
}
}
}
在此情况下,任何有助于理解最佳方法的帮助都将不胜感激
# 1 楼答案
如果没有,从服务访问活动是不好的。您可以使用binder在活动中获取服务实例,然后可以在服务中注册一些回调以与活动通信。查看此链接以获取示例https://gist.github.com/ErikHellman/4b6ecc87d1b37c9809d1