[英]How can I check if GPS is enabled before I try to use it
I have the following code and it's not good because sometimes GPS takes very long 我有以下代码,但效果不好,因为有时GPS需要很长时间
How can I do the following: 如何执行以下操作:
I can do this with my own logic using a time or Thread.sleep but I think there might be a more stabndard way 我可以使用时间或Thread.sleep以自己的逻辑进行此操作,但我认为可能会有更稳定的方法
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.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.
locationCallback(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);
Just using this, you can check GPS
availability 只需使用此功能,即可查看GPS
可用性
LocationManager mlocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);;
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
There's no standard way, you have to do it on your own with the help of: 没有标准的方法,您必须借助以下方法自行完成:
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
//Do what you need if enabled...
}else{
//Do what you need if not enabled...
}
And this permission in manifest: 并且此权限在清单中:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
As recommendation if GPS is not enabled, usually the standard specifies to popup the Location Settings Activity so the user can specifically enable it... 作为建议,如果未启用GPS,通常标准会指定弹出“位置设置活动”,以便用户可以专门启用它。
Hope this helps. 希望这可以帮助。
Regards! 问候!
Think you could use the code in my answer to: Location servise GPS Force closed 认为您可以在我的答案中使用以下代码: 位置服务GPS强制关闭
It gives you a callback method for GPS first fix and location changes that can be very convenient. 它为您提供了一种用于GPS首次定位和位置更改的回调方法,该方法非常方便。 This also makes it easy to change the implementation of GPSTracker to switch to network if GPS takes too long to get a first fix. 如果GPS花费太长时间无法获得首次修复,这也可以轻松更改GPSTracker的实现以切换到网络。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.