我正在实现我的应用程序,它可以为用户获取位置。但是,我发现 LocationManager 并不总是适用于所有设备,你知道,有很多不同的 Android 设备。然后我正在考虑获取原始 gps 数据并将其发送到位置网络服务以获取位置会更好。
在环顾四周之后,我没有得到一个强大的解决方案,有什么想法吗?我真的很好奇市场上的一些 GPS 应用程序如何在每台设备上运行。
代码片段
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener locationListener = new MyLocationListener(locationManager);
locationListener.start();
听众,
public class MyLocationListener implements LocationListener{
public static int PERMISSION_DENIED = 1;
public static int POSITION_UNAVAILABLE = 2;
public static int TIMEOUT = 3;
protected LocationManager locationManager;
protected boolean running = false;
public MyLocationListener(LocationManager locationManager )
{
this.locationManager = locationManager;
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider '" + provider + "' disabled.");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "Location provider "+ provider + " has been enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "The status of the provider " + provider + " has changed");
if (status == 0) {
Log.d(TAG, provider + " is OUT OF SERVICE");
}
else if (status == 1) {
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
Log.d(TAG, provider + " is AVAILABLE");
}
}
public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!");
Log.d(TAG, "latitude = "+location.getLatitude()+" altitude = "+location.getAltitude());
}
public void start() {
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
this.running = true;
Log.d(TAG,"using gps");
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 600000, 0, this);
} else {
Log.d(TAG, "GPS provider is not available.");
}
}
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true;
Log.d(TAG,"using network");
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 600000, 10, this);
} else {
Log.d(TAG, "Network provider is not available.");
}
}
}
private void stop() {
if (this.running) {
this.locationManager.removeUpdates(this);
this.running = false;
}
}
/**
* Destroy listener.
*/
public void destroy() {
this.stop();
}
有时, onStatusChanged 什么也得不到。