如何使用GoogleApiClient获取位置?

时间:2015-12-15 18:04:37

标签: android location google-api-client location-services

我试图使用GoogleApiClient lib.im尝试使用以下代码在Android中获取位置。但是没有任何内容可以指定给 clientLoc 。我的代码中有任何错误吗?任何人都可以帮助我吗?

Lat = (TextView) findViewById(R.id.textView2);
Lng = (TextView) findViewById(R.id.textView4);
getLoc = (Button) findViewById(R.id.button);
clientLoc=new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();



getLoc.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        MobLoc = LocationServices.FusedLocationApi.getLastLocation(clientLoc);
        try {

        Lat.setText(String.valueOf(MobLoc.getLatitude()));
        Lng.setText(String.valueOf(MobLoc.getLongitude()));

        Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
        }
        catch (Exception e){
            Toast.makeText(MainActivity.this," "+e.getMessage(),Toast.LENGTH_LONG);

    }
});

1 个答案:

答案 0 :(得分:1)

我看起来你没有在google api客户端上调用Connect。如果不先调用connect,则无法从客户端请求位置。在您的google api客户端上调用connect,然后在onConnected回调中为您的按钮设置点击监听器。

private void getGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    getLoc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MobLoc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            try {

            Lat.setText(String.valueOf(MobLoc.getLatitude()));
            Lng.setText(String.valueOf(MobLoc.getLongitude()));

            Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
            }
            catch (Exception e){
            Toast.makeText(MainActivity.this," "+e.getMessage(),Toast.LENGTH_LONG);

        }
    });
}

快乐编码