我想使用gps提供程序获取设备的当前位置,但这实际上等待gps位置改变.
所以我有一个简单的应用程序来监听位置的变化.这可以立即使用NETWORK_PROVIDER,但是对于GPS_PROVIDER,我等了15分钟并且没有发生任何动作.
我正在使用API级别8.
public class MainActivity extends Activity {
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) this.findViewById(R.id.textView1);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); // this works fine
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
Date today = new Date();
Timestamp currentTimeStamp = new Timestamp(today.getTime());
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: " + "\n Latitude: "
+ location.getLatitude() + "\n Longitude: "
+ location.getLongitude() + "\n Accuracy: "
+ location.getAccuracy() + "\n CurrentTimeStamp "
+ currentTimeStamp + "\n Altitude: "
+ location.getAltitude() + "\n Bearing"
+ location.getBearing() + "\n Speed"
+ location.getSpeed() + "\n ";
Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG)
.show();
tv.append(str);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Error onProviderDisabled",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "onProviderEnabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "onStatusChanged",
Toast.LENGTH_LONG).show();
}
}
}
我确实把权限放在了清单中,所以这不是问题所在.
最佳答案 你在里面测试吗?除非您在外面,否则您可能根本无法获得GPS锁定,这意味着手机会尽可能频繁地锁定(因为您在requestLocationUpdates调用中指定了最小时间和距离0和0) ).
不幸的是,你只需要等待设备获得GPS锁定,如果由于缺少信号而没有,你就会等待.您可以做的第一件事就是尝试获取GPS提供商的最后一个已知位置.如果设备最近有GPS锁并存储了一个位置,这将返回一个位置:
Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
除此之外,您应该尝试从网络提供商处获取位置,因为这可能比GPS更快地返回位置,正如您已经观察到的那样.这是因为只要您有无线信号,就可以在任何地方(包括室内)使用丰富的位置数据源(手机信号塔和WIFI).