2017-07-24 97 views

回答

0

provider = locationManager.getBestProvider(new Criteria(), false);

你的enabledOnly參數提供false,所以它可能是返回未啓用的供應商。然後通過javadocs返回getLastKnownLocation它將返回null:「如果提供程序當前被禁用,則返回null。」

+0

你的建議我應該enabledOnly值更改爲真?我試過了。也不起作用。 –

0

除了位置管理器,您可以使用FusedLocationApi

和代碼樣本是這裏

protected synchronized void buildGoogleApiClient() { 
    // Toast.makeText(getContext(), "buildGoogleApiClient", Toast.LENGTH_SHORT).show(); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    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. 


     return; 
    } 
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     //place marker at current position 
     // Log.e("x", mLastLocation.getLongitude() + ""); 
     //Log.e("y", mLastLocation.getLatitude() + ""); 
     currentLocation = mLastLocation; 


    } 

    LocationRequest mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(5000); //5 seconds 
    mLocationRequest.setFastestInterval(5000); //3 seconds 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    mLocationRequest.setSmallestDisplacement(50F); //1/10 meter 

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

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onLocationChanged(Location location) { 

    currentLocation = location; 

} 

參數,你需要

private GoogleApiClient mGoogleApiClient; 
private Location currentLocation; 

,並呼籲buildGoogleApiClient上的活動或片段onCreateMethode()