Android - 无法与Google Play服务建立联系

时间:2016-12-26 13:08:42

标签: java android google-play-services

我想通过使用play service api获取用户的当前位置。但总是调用onConnectionFailed()方法。我已使用SHA-1密钥添加了 google-services.json 文件。但它显示了在onConnectionFailed()方法中编写的Toast消息。我该如何解决?

这是我的代码 -

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //setup GoogleApiClient
        setupGoogleApiClient();

    }

    }
    }

    //setup GoogleApiClient object
    private void setupGoogleApiClient() {
        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        mGoogleApiClient.connect();
    }

    protected void onStart() {
        super.onStart();
    }

    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(this, "Connected with google play service",        Toast.LENGTH_LONG).show();

    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Connection suspended with google play service", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "Failed to connect with google play service", Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:2)

尝试更改gradle文件中的播放服务版本, 如果您正在使用

compile 'com.google.android.gms:play-services:10.0.1'

尝试

compile 'com.google.android.gms:play-services:8.x.x'

和其他组合。

  

注意: - 将“x”替换为合适的值