将Android应用程序中的GPS功能外包给单独的类

时间:2011-04-14 11:49:55

标签: java android gps location

我跟着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);
}
}

我错过了什么,做错了什么?

1 个答案:

答案 0 :(得分:0)

在onCreate方法中设置无限循环是错误的想法。您的问题很可能是因为onCreate永远不会完成并将控制权交还给操作系统而引起的。如果这导致Force Close错误,我不会感到惊讶。

您可能需要做的是创建一项服务,该服务将执行您的位置监控并从那里更新您的活动。