我计划在 Activity 中添加一个按钮,单击该按钮将启动服务。但是,需要启用 GPS 才能使服务正常工作,因此如果禁用 GPS,我想禁用该按钮。有没有办法让 android 在启用/禁用 GPS 时通知我的 Activity ,以便我可以相应地启用/禁用按钮?
最佳答案
此链接描述了如何创建位置监听器: 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);
requeSTLocationupdates 中的第二个和第三个参数你可能应该做得很大,这样你就不会得到位置更新,因为你并不真正关心这些,只关心提供商启用/禁用的更改。
关于android - 在 Activity 中捕获系统事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621707/