检索的位置始终为空

时间:2017-03-23 19:11:36

标签: android android-studio google-api

我正在通过本教程学习Android中的位置服务:https://www.youtube.com/watch?v=nwdwzQhutdo

我拥有基于视频的所有正确代码,但位置始终为空。我似乎无法弄清楚为什么会这样。

输出:Location could not be detected. Try again later.

CODE

public void onCreate() {
    getLocation();
    locationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (null != mGoogleApiClient && mGoogleApiClient.isConnected()) {
                try {
                    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    if (location != null) {
                        Toast toast = Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()), Toast.LENGTH_SHORT);
                        toast.show();
                    } else {
                        Toast toast = Toast.makeText(getApplicationContext(), "Location could not be detected. Try again later.", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                } catch(SecurityException e) {
                    Toast toast = Toast.makeText(getApplicationContext(), "ERROR: Could not detect location. Please check location settings.", Toast.LENGTH_SHORT);
                    toast.show();
                }
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "Error: Not connected to google play services", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    });
}

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

1 个答案:

答案 0 :(得分:1)

好的,这是步骤。首先,添加依赖项:

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

复制以下代码,你会理解它,它们只是基础:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private final String LOG_TAG = "TestApp";
private TextView tvLongitude, tvLatitude;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

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

    checkPermission();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    tvLongitude = (TextView) findViewById(R.id.tvLongitude);
    tvLatitude = (TextView) findViewById(R.id.tvLatitude);
}

public void checkPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

                onResume();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

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

@Override
protected void onResume() {
    super.onResume();

    checkPermission();
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        checkPermission();
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(LOG_TAG, "GoogleApiClient connection has been suspended");

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i(LOG_TAG, "GoogleApiClient connection has been failed");
    Log.i(LOG_TAG, "" + connectionResult);

}

@Override
public void onLocationChanged(Location location) {
    Log.i(LOG_TAG, location.toString());
    tvLongitude.setText(Double.toString(location.getLongitude()));
    tvLatitude.setText(Double.toString(location.getLatitude()));
}
}

询问任何您不理解的部分。我猜它很直接。