onReceive 在不应该被调用的时候被调用

发布于 2024-10-11 16:00:59 字数 1061 浏览 4 评论 0原文

几秒钟前,我正在调试我的小部件,我发现即使我的小部件不在主屏幕上,也会调用 onReceive 方法(它侦听 WIFI_STATE_CHANGED_ACTION ) 。即使我的小部件的进程没有运行,它也会启动并调用该方法。 清单中的代码如下:

<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

    <receiver android:name="WiFiWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>

        <meta-data android:name="android.appwidget.provider" 
                   android:resource="@xml/widget_info" />
    </receiver>

</application>

方法 onReceive 只需调用另一个方法 toggleState (以更改 wifi 状态),然后更新小部件图像(从关闭图像到打开图像,反之亦然)。

显然,如果小部件实际上并未在主屏幕上处于活动状态,则调用toggleState和updateWidget(以及完整的onReceive)这两个方法是无用的。

因此,我希望仅当我的onReceive时才调用我的onReceive小部件有效地放置在主屏幕上..有办法做到这一点吗? :)

预先感谢您的回答

some seconds ago I was debugging my widget and I've found that the onReceive method is called even if my widget isn't on the home screen (it listens for WIFI_STATE_CHANGED_ACTION ). Even if the process of my widget isn't running, it will be started and the method called.
The code in the manifest is the following:

<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

    <receiver android:name="WiFiWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>

        <meta-data android:name="android.appwidget.provider" 
                   android:resource="@xml/widget_info" />
    </receiver>

</application>

The method onReceive simply calls another method toggleState ( to change the wifi state ) and then updates the widget image ( from off to on image or viceversa ).

Obviously the call of the two methods toggleState and updateWidget ( and so the complete onReceive ) are useless if the widget isn't actually active on the home screen..

So, I want my onReceive called only if my widget is effectively placed on home screen..there's a way to do this? :)

thanks in advance for the answers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光是把杀猪刀 2024-10-18 16:00:59

为什么你的广播接收器不会被调用?这就是当您的进程/活动未运行时调用广播接收器的要点。

如果您只想在特定时间调用它,则必须在小部件的代码中注册它,并在您不想接收广播时取消注册它。

Why wouldn't your broadcast receiver be called? That's the point of a broadcast receiver is to be called when your process/activity isn't running.

If you only want it called at certain times, you have to register it in code in your widget, and unregister it when you don't want to receive broadcasts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文