簡體   English   中英

在Android中獲取更新的位置

[英]Getting an updated location in Android

我正在使用下面顯示的代碼來獲取每次單擊按鈕時位置的更新值。 恢復活動后,我每秒都會收到一次更新,因此,當我調用getLastKnownLocation時,我希望其位置已在最后一秒更新。

那是正確的方法嗎?

我希望每次執行“ geo fix”命令時都會觸發onLocationChanged事件(或者自1s之后每隔1s進行一次更新,最多在1s之后觸發),但這僅是第一次觸發。 為什么?

歡迎任何幫助/建議!

謝謝

package org.digitalfarm.atable;

...

public class Atable extends Activity {
    private Button mSearchButton;
    private TextView mytext;
    private LocationManager locationManager;    


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);   

        setContentView(R.layout.main);

        mSearchButton = (Button)this.findViewById(R.id.button);

        mytext = (TextView) findViewById(R.id.dude);

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        final Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);               


        mSearchButton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {

                  String provider = locationManager.getBestProvider(criteria, true);

                  Location location = locationManager.getLastKnownLocation(provider);             

          }
        });
    }

     //Start a location listener
    LocationListener onLocationChange=new LocationListener() {
        public void onLocationChanged(Location loc) {
            //sets and displays the lat/long when a location is provided
            String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();   
            mytext.setText(latlong);
        }

        public void onProviderDisabled(String provider) {
        // required for interface, not used
        }

        public void onProviderEnabled(String provider) {
        // required for interface, not used
        }

        public void onStatusChanged(String provider, int status,
        Bundle extras) {
        // required for interface, not used
        }
    };

    //pauses listener while app is inactive
    @Override
    public void onPause() {
        super.onPause();
        locationManager.removeUpdates(onLocationChange);
    }

    //reactivates listener when app is resumed
    @Override
    public void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,100.0f,onLocationChange);
    }
}

requestLocationUpdates中指定的時間是最短的時間間隔,最多將發生一次更新。 因此,您最多每秒注冊一次更新,但是實際更新可能花費的時間更多,而且,對此不作任何保證。

從文檔中:

minTime-通知的最小時間間隔,以毫秒為單位。 該字段僅用作節省電量的提示, 位置更新之間的實際時間可能大於或小於此值。

嘗試將該時間間隔設置為0,如果沒有其他問題(盡管對我來說似乎一切正常),則應“盡可能頻繁地”開始獲取更新。

暫無
暫無

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

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