1
我跟在http://developer.android.com/guide/topics/location/obtaining-user-location.html上,並且在onCreate方法中處於活動狀態時工作正常。將Android應用程序中的GPS功能外包給一個單獨的類
然後我想將這個功能外包給名爲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);
}
}
我在想什麼,做錯了什麼?
我做了一些日誌記錄,發現LocationHelper-class中的loc是** always ** null,這在將相同的代碼放在activity中時不會發生。 – mhk 2011-04-14 12:19:01
但這可能是因爲您的上下文尚未完全初始化,因爲您沒有將控制權交還給Android。 – 2011-04-14 12:24:28
我沒有做到這一點,而(真)......也不工作。 – mhk 2011-04-14 12:27:03