android - 在 Activity 中捕获系统事件

标签 android android-activity android-event

我计划在 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/

相关文章:

java - stringByEvaluatingJavascriptFromString(iOS 方法,Android 等效方法是什么?)

java - 在启动Intent之前更改布局内容,例如文本和图像

android - ACRA 集成和 Google 云端硬盘

android - 如何避免 Android 库项目中未使用的资源和代码进入我的 APK?

java - 如何在 Activity 顶部显示 "window/subactivity/dialog"但将焦点保持在 Activity 中

android - Facebook 请求代码

Android 11、自定义标签和 FLAG_ACTIVITY_CLEAR_TOP

android - 设置频率属性 RRULE 以运行事件一次

android - 如何在不共享源代码的情况下创建和使用 Android 库?