2017-08-27 94 views
-1

我一直在嘗試使用融合位置API來獲取用戶的位置,完全像這裏所描述的https://developer.android.com/training/location/retrieve-current.html 但我沒有得到任何結果。有時它可以工作,但大多數情況下它不工作,並且這只是在虛擬設備上,真正的設備上沒有發生。 這裏是我的MainActivity.java:如何獲取用戶在android上的當前位置?

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     ActivityCompat.requestPermissions(this, 
       new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
       10); 
     ActivityCompat.requestPermissions(this, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       10); 
     // 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; 
    } 
    Log.v("","the beg"); 
    mFusedLocationClient.getLastLocation() 
      .addOnSuccessListener(this, new OnSuccessListener<Location>() { 
       @Override 
       public void onSuccess(Location location) { 
        // Got last known location. In some rare situations this can be null. 
        if (location != null) { 
         // ... 
         Log.v("", String.valueOf(location.getLatitude())); 
         Log.v("", String.valueOf(location.getLongitude())); 
        } 
       } 
      }); 
    Log.v("","the end"); 
} 

} 這我Android.m

+0

@hassanitohajj in'onSucces'方法你有這個嗎? if(location!= null)Geocoder geoCoder = new Geocoder(getBaseContext(),Locale.getDefault());''你有一些'...'因此我只是在問。 –

回答

0

首先,定義一個LocationListener的處理位置的變化。

private final LocationListener mLocationListener = new LocationListener() { 
    @Override 
    public void onLocationChanged(final Location location) { 
     //your code here 
    } 
}; 

然後得到的LocationManager,並要求位置更新

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
LOCATION_REFRESH_TIME, 
      LOCATION_REFRESH_DISTANCE, mLocationListener); 
} 

最後請確保您所添加的權限的清單,

對於使用基於唯一的網絡位置使用一個

對於基於GPS的位置,這一個