簡體   English   中英

等待當前位置-GPS-Android開發人員

[英]Wait for current location - GPS - Android Dev

我必須等待獲取當前位置,就像您在Google地圖中一樣,它會請求您的位置。 如果無法找到任何位置,則通知錯誤,而不執行任何操作。

我在這里和網絡上都閱讀了答案,但所有人都說我必須使用getLastKnownLocation方法,但是我不需要這個,我只需要當前位置。 如果沒有,我什么也不會做。

從昨天開始閱讀: 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) {}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM