簡體   English   中英

將Android應用中的GPS功能外包給一個單獨的類

[英]Outsource GPS functionality in android app to a separate class

我遵循了http://developer.android.com/guide/topics/location/obtaining-user-location.html ,當處於onCreate方法中的活動中時,此方法工作正常。

然后,我想在一個單獨的名為LocationHelper的類中將此功能外包。

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class LocationHelper {

public Context mContext;
public Location loc;

public LocationHelper (Context mContext){
    this.mContext = mContext;

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager)     mContext.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
            setLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };

    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

public void setLocation(Location location) {
    this.loc = location;
}

public Location getLocation() {
    return this.loc;
}
}

在活動中,我這樣做; 基本上,我想從助手類中提取GPS坐標(用於測試!)並顯示它。 問題是,位置始終為空。

public class GraffitiWall extends Activity {

private TextView tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = new TextView(this);

    LocationHelper gpsie = new LocationHelper(this);
    while (true){
        makeUseOfNewLocation(gpsie.getLocation());
    }
}

public void makeUseOfNewLocation(Location loc){
    if (loc == null){return;}
    tv.setText("" + loc.getLatitude());
    setContentView(tv);
}
}

我錯過了什么,做錯了什么?

在您的onCreate方法中放入無限循環是一個主意。 您的問題很可能是由於onCreate無法完成並將控制權傳遞回OS而引起的。 如果這引起強制關閉錯誤,我不會感到驚訝。

也許您需要做的就是創建一個服務,該服務將對您的位置進行監控並從那里更新您的活動。

暫無
暫無

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

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