我正在制作一个小测试程序来掌握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");
}
}
答案 0 :(得分:2)
我明白了!
原来,我只是出去了:)
答案 1 :(得分:1)
如果禁用GPS,它将始终返回null。请参阅LocationManager.getLastKnownLocation
的Android文档答案 2 :(得分:0)
在这种情况下,您应该使用LocationListener。因为它可能会发生,你可能无法从getLastKnownLocation()获取位置。
只需调用requestLocationUpdates,您将获得LocationListener
中的回调