我关注了http://developer.android.com/guide/topics/location/obtaining-user-location.html当处于 onCreate 方法的 Activity 中时,这工作得很好。
然后我想将此功能外包到一个名为 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;
}
}
在 Activity 中我这样做;基本上我想从我的助手类中提取(出于测试目的!)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 永远不会完成并将控制权传递回操作系统而引起的。如果这导致强制关闭错误,我不会感到惊讶。
也许您需要做的是创建一项服务来监控您的位置并从那里更新您的 Activity 。
关于java - 将 Android 应用程序中的 GPS 功能外包给一个单独的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662746/