简体   繁体   中英

Android Studio Emulator crashes on LocationServices.fusedLocationApi

So I have a Google Maps application in android studio and I am trying to set it up. I looked at Treehouse how they set it up with googles own location provider and everything that is necessary http://blog.teamtreehouse.com/beginners-guide-location-android

I have done everything it says and it works fine on my cellphone but the emulator crashes on startup and it says the fault is in the line

LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient, this.mLocationRequest, this);

I dont know what I should do. I've even used the console to geo fix a location to the gps in the emulator but nothing. Here is my complete code

public class Guide extends AppCompatActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener


private GoogleMap           mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient     mGoogleApiClient;
private LocationRequest     mLocationRequest;
private LatLng              currentPos;

private boolean             centerCamera;
private boolean             isSatelliteChecked = false;

public static final String TAG = Guide.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_guide);
    this.centerCamera = true;
    setUpMapIfNeeded();

    // Create the Google API Client
     mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1000); // 1 second, in milliseconds




}

@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem checkable = menu.findItem(R.id.map_type);
    checkable.setChecked(isSatelliteChecked);
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{// Inflate the menu; this adds items to the action bar if it is
    // present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.menu_settings:

            return true;
        case R.id.map_type:
            isSatelliteChecked = !item.isChecked();
            item.setChecked(isSatelliteChecked);
            if(isSatelliteChecked)
            {
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            }
            else
            {
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            }
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onResume()
{
    super.onResume();
    setUpMapIfNeeded();
    mGoogleApiClient.connect();
    this.mMap.setMyLocationEnabled(true);
    if (this.currentPos != null)
    {
       this.mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPos, 16));
    }
}

@Override
protected void onPause()
{
    if (this.mGoogleApiClient.isConnected())
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(this.mGoogleApiClient, this);
        this.mGoogleApiClient.disconnect();
    }
    if (this.mMap!=null)
    {
        mMap.setMyLocationEnabled(false);
        this.centerCamera = true;
    }
    super.onPause();

}
/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded()
{
    // Do a null check to confirm that we have not already instantiated the map.
    if (this.mMap == null)
    {
        // Try to obtain the map from the SupportMapFragment.
        this.mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (this.mMap != null)
        {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    this.mMap.setMyLocationEnabled(true);
    this.mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

}


private void handleNewLocation(Location location)
{
    Log.d(this.TAG, location.toString());
}

@Override
public void onConnected(Bundle bundle)
{
    Log.i(this.TAG, "Location services connected.");
    Location location = LocationServices.FusedLocationApi.getLastLocation(this.mGoogleApiClient);
    if (location == null)
    {
        LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient, this.mLocationRequest, this);
    }
    else
    {
        handleNewLocation(location);
    }
}

@Override
public void onConnectionSuspended(int i)
{
    Log.i(this.TAG, "Location services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
    if (connectionResult.hasResolution())
    {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e)
        {
            e.printStackTrace();
        }
    }
    else
    {
        Log.i(this.TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onLocationChanged(Location location)
{
    handleNewLocation(location);
}

Your emulator might not have google play services. This may help: How to download Google Play Services in an Android emulator?

This solved the problem for me.

In gradle build I check that both play-services have the same version. Here 10.2.6

compile 'com.google.android.gms:play-services-maps:10.2.6' compile 'com.google.android.gms:play-services-location:10.2.6'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM