Skip to content

Most visited

Recently visited

navigation

随需操纵广播接收器

监控设备状态变化的最简单方法是,为您要监控的每个状态创建一个 BroadcastReceiver,并在您的应用清单文件中注册每个接收器。然后在每个接收器内,您只需根据当前设备状态重新安排定期闹铃。

此方法的副作用是,每次触发任何一个接收器时,您的应用都会唤醒设备—唤醒频率可能远超所需水平。

更好的方法是在运行时停用或启用广播接收器。这样一来,您就可以将在清单文件中声明的接收器用作被动闹铃,只在必要时由系统事件触发。

通过切换和级联状态变化接收器提高效率

您可以利用 PackageManager 在清单文件中所定义的任何组件上切换启用状态,包括您想启用或停用的任何一个广播接收器,如以下代码段中所示:

ComponentName receiver = new ComponentName(context, myReceiver.class);

PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP)

如果您确定已失去连接,可以利用此技巧停用除连接变化接收器以外的所有接收器。 相反,连接后您可以立即停止侦听连接变化,只是在即将执行更新和重新安排定期更新闹铃前确认是否处于在线状态。

您可以使用同一方法推迟需要更高带宽才能完成的下载。只需启用一个广播接收器,让它仅在连接 Wi-Fi 后再侦听连接变化并启动下载。

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Follow Google Developers on WeChat

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)