使用API​​ 22获取用户位置lat lng

时间:2016-11-30 12:31:38

标签: android geolocation

尝试像下面的代码一样简单的东西似乎不起作用:

我总是在日志中找到“No Location :(”

我错过了什么吗?

public class MainActivity extends AppCompatActivity implements LocationListener {

LocationManager locationManager;
String provider;

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

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

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

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Location location = locationManager.getLastKnownLocation(provider);

    if(location != null){
        Log.i("Location","Location achieved");
    }else{
        Log.i("Location","No location :(");
    }
}

2 个答案:

答案 0 :(得分:2)

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
onCreate()中的

      new GoogleApiClient.Builder(context)
         .addApi(LocationServices.API)
         .addConnectionCallbacks(this)
         .addOnConnectionFailedListener(this)
         .build()

活动中的总代码:

public class MainActivity extends ActionBarActivity implements
            ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
         @Override
    public void onConnected(Bundle connectionHint) {

    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}
        @Override
        public void onLocationChanged(Location location) {
            mCurrentLocation = location;
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateUI();
        }

        private void updateUI() {
            mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
            mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
            mLastUpdateTimeTextView.setText(mLastUpdateTime);
        }
@Override
public void onResume() {
    super.onResume();
    if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}
    }

停止接收更新:

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

答案 1 :(得分:1)

如果您正在运行模拟器,请确保从模拟器设置发送位置事件。不过,getLastKnownLocation总是可以返回null。您可以使用LocationManager#requestLocationUpdates来收听任何位置更改。