我正在制作一个小测试程序来掌握 Android GPS 的窍门,看看电池对学校项目的影响。我只是想让我的设备通过打印出最后检测到的已知位置的纬度来检测我的位置。但该位置始终在 onResume() 回调中返回 null。
任何帮助是极大的赞赏。
TextView Updates;
long start = -1;
long battStart = -1;
long stop = -1;
PowerManager.WakeLock wl;
LocationManager locationManager;
LocationListener locationListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Updates = (TextView) findViewById(R.id.textView);
Updates.append("\n onCreate()");
batteryLevel();
start = System.currentTimeMillis();
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Updates.append("\n Found a place! "+location.getLatitude()+","+location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Updates.append("yes"+provider);
}
public void onProviderDisabled(String provider) {
Updates.append("No"+provider);
}
};
}
protected void onStart() {
super.onStart();
Updates.append("\n onStart()");
// Set up a wake lock
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag2");
this.wl.acquire();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
protected void onResume() {
super.onResume();
batteryLevel();
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
Updates.append(String.valueOf(loc.getLatitude()));
} else {
Updates.append("loc is null");
}
}