我打算在活动中设置一个按钮,点击后即可启动服务。但是,需要启用GPS以使服务完成其工作,因此如果禁用GPS,我希望禁用该按钮。有没有办法让Android在启用/禁用GPS时通知我的活动,以便我可以相应地启用/禁用按钮?
答案 0 :(得分:1)
此链接描述了如何创建位置监听器: http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/
如果网站将来发生故障,我已经将重要部分复制到了下方。第一步是创建LocationListener:
private final class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location locFromGps) {
// called when the listener is notified with a location update from the GPS
}
@Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
// Dim the button here!
}
@Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
// Brighten the button here!
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
}
然后你想要注册那个听众。这可能应该放在你的onCreate()
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
请求位置中的第二个和第三个参数更新你应该做的很大,所以你不能获得locationupdates,因为你并不真正关心那些,只有提供者启用/禁用更改。
答案 1 :(得分:0)
请使用此代码获取GPS状态。在活动的onResume中使用此代码
private LocationManager mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean GPSprovider = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
根据GPSProvider,您可以启用和禁用该按钮。
答案 2 :(得分:0)
试试这个
final String GpsProvider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (GpsProvider.equals(""){
//No GPS
}else{
//GPS available
}