还有其他方法可以连接Google API客户端吗?
我使用自动完成的地方,我必须在FRAGMENT的某处使用此代码
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this).build();
我的问题
enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this).build();
我不能处理它,因为当我用this
替换getActivity()
时我有很多问题
感谢您的帮助,如果这个问题很愚蠢,我很抱歉。
如果你想使用enableAutoManage
,那么你必须让你的活动扩展FragmentActivity
。它所做的回调是GoogleApiClient
自动管理工作所必需的。因此,最简单的解决方案是将extends FragmentActivity
添加到您的活动中。然后你的演员表不会失败并导致应用程序在运行时崩溃。
另一种解决方案是自己管理api客户端。您将从构建器中删除enableAutoManage
行,并确保您自己从客户端connect
/ disconnect
。最常见的地方是onStart()
/ onStop()
。就像是...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addApi(Places.GEO_DATA_API)
.addConnectionCallbacks(this).build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
很抱歉迟到的回复,但您可以扩展AppCompatActivity而不是扩展FragmentActivity ...
public class YourActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
.....
mCredentialsApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.enableAutoManage(this,this)
.addApi(Auth.CREDENTIALS_API)
.build();
如果您的片段在FragmentActivity或AppCompatActivity中运行,您可以执行以下操作:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage((FragmentActivity) getActivity() /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// your code here
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
我的解决方案类似于接受的答案,除了我使用Builder的第二个签名,以便connectionFailedListener也发送给构造函数。
分别是onStart()和onStop()中的mGoogleApiClient.connect()和mGoogleApiClient.disconnect()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this /*context*/ , this /*connectedListener*/, this /**connectionFailedListener/)
.addApi(Places.GEO_DATA_API)
.build();
}