在片段中使用enableAutoManage()

问题描述 投票:24回答:4

还有其他方法可以连接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()时我有很多问题

感谢您的帮助,如果这个问题很愚蠢,我很抱歉。

android android-fragments google-places-api google-api-client
4个回答
61
投票

如果你想使用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();
}

2
投票

很抱歉迟到的回复,但您可以扩展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();

1
投票

如果您的片段在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();

0
投票

我的解决方案类似于接受的答案,除了我使用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();
}
© www.soinside.com 2019 - 2024. All rights reserved.