等待当前的位置 - GPS - Android开发(Wait for current loca

2019-07-29 08:38发布

我不得不等待获取当前位置,只是当你在谷歌地图一样,它为您的位置要求。 如果它不能得到任何位置告知错误,什么也不做。

我在这里和网络阅读的答案,但所有的说,我不得不使用getLastKnownLocation的方法,但我不需要这个,我只需要在当前位置。 如果没有,我没有做任何事情。

Answer 1:

从昨天阅读: GPS的Android -获得定位只有一次

但这里是你可以得到当前位置:

public class Example extends Activity implements LocationListener {
    LocationManager mLocationManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
            // Do something with the recent location fix 
            //  if it is less than two minutes old,
            //  otherwise wait for the update below
        }
    }

    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
            // You need to call this whenever you are done:
            // mLocationManager.removeUpdates(this);
        }
    }

    // Required functions    
    public void onProviderDisabled(String arg0) {}
    public void onProviderEnabled(String arg0) {}
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}


文章来源: Wait for current location - GPS - Android Dev
标签: android gps