• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Manipulating Broadcast Receivers On Demand
2parent.title=Optimizing Battery Life
3parent.link=index.html
4
5trainingnavtop=true
6
7previous.title=Determining and Monitoring the Connectivity Status
8previous.link=connectivity-monitoring.html
9
10@jd:body
11
12<div id="tb-wrapper">
13<div id="tb">
14
15<h2>This lesson teaches you to</h2>
16<ol>
17  <li><a href="#ToggleReceivers">Toggle and Cascade State Change Receivers to Improve
18Efficiency</a></li>
19</ol>
20
21
22<h2>You should also read</h2>
23<ul>
24  <li><a href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters</a>
25</ul>
26
27</div>
28</div>
29
30<p>The simplest way to monitor device state changes is to create a {@link
31android.content.BroadcastReceiver} for each state you're monitoring and register each of them in
32your application manifest. Then within each of these receivers you simply reschedule your recurring
33alarms based on the current device state.</p>
34
35<p>A side-effect of this approach is that your app will wake the device each time any of these
36receivers is triggered&mdash;potentially much more frequently than required.</p>
37
38<p>A better approach is to disable or enable the broadcast receivers at runtime. That way you can
39use the receivers you declared in the manifest as passive alarms that are triggered by system events
40only when necessary.</p>
41
42
43<h2 id="ToggleReceivers">Toggle and Cascade State Change Receivers to Improve Efficiency </h2>
44
45<p>Use can use the {@link android.content.pm.PackageManager} to toggle the enabled state on any
46component defined in the manifest, including whichever broadcast receivers you wish to enable or
47disable as shown in the snippet below:</p>
48
49<pre>ComponentName receiver = new ComponentName(context, myReceiver.class);
50
51PackageManager pm = context.getPackageManager();
52
53pm.setComponentEnabledSetting(receiver,
54        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
55        PackageManager.DONT_KILL_APP)</pre>
56
57<p>Using this technique, if you determine that connectivity has been lost, you can disable all of
58your receivers except the connectivity-change receiver. Conversely, once you are connected you can
59stop listening for connectivity changes and simply check to see if you're online immediately before
60performing an update and rescheduling a recurring update alarm.</p>
61
62<p>You can use the same technique to delay a download that requires higher bandwidth to complete.
63Simply enable a broadcast receiver that listens for connectivity changes and initiates the
64download only after you are connected to Wi-Fi.</p>
65