1. 程式人生 > >Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime

Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime

BroadcastReceivers are good when you want to be notified about system events. But sometimes you do need to know about an event only once or for a short period of time.

A dynamically registered receiver doesn't cut it because the Activity and it's dynamically registered broadcast receiver might long be dead when the event occurs. The only way to achieve this is by enabling and disabling broadcast receivers in your code.

Enabling or Disabling BroadcastReceivers

You enable or disable receivers by using methods of the PackageManager class. With this class you can enable and disable app components at runtime:


PackageManager pm = getPackageManager();
ComponentName compName = 
      new ComponentName(getApplicationContext(), 
            YourReceiver.class);
pm.setComponentEnabledSetting(
      compName,
      PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
      PackageManager.DONT_KILL_APP);

There are three states the PackageManager offers for this:

Supported states of setComponentEnabledSetting()
COMPONENT_ENABLED_STATE_DEFAULT Sets the state to the manifest file value
COMPONENT_ENABLED_STATE_DISABLED Sets the state to disabled
COMPONENT_ENABLED_STATE_ENABLED Sets the state to enabled

By default the PackageManager kills your app immediately, since a component state change could lead to unpredictable situations. The flag DONT_KILL_APP prevents this from happening and is safe to use for BroadcastReceivers. Of course if you do not use the DONT_KILL_APP-flag, you will spot your mistake even with the most cursory of testings 🙂

Disabling BroadcastReceivers by default

If you want to enable your receiver at runtime, you can set the state to disabled initially. You can do so in the manifest file:


<receiver
   android:name=".YourReceiver"
   android:enabled="false" >
   <!-- your intent filter -->
</receiver>

When to use this

The basic reason why you should do this, is that you want to preserve valuable resources on your user's devices. You do not want to drain the battery by running code that is not relevant to your user. Most often you can achieve this by using a dynamically registered receiver. But this does not always work.

Three examples where you should explicitly use the PackageManager-solution presented above:

1. You might need to know about the next boot, but only the next one. In this case you cannot use a dynamically registered receiver. You have to use a statically registered one. But you do not want to run it on every boot completion. Which means that you have to disable the receiver after it's first run.

2. If one or more receivers depend on the state of a specific system service you can disable all of them for as long as the necessary service is not in the desired state. This could be true for network connectivity, while waiting for a GPS fix, for missing Bluetooth availabilty and such.

3. You intend to use notifications - but only if the app is not currently active. In this case your BroadcastReceiver has to be enabled by default. But you would disable it in your Activities' onResume() method and re-enable it in the onPause() method.

See also Reto Meier's blog post about location-based apps and have a thorough look at the accompanying source code. He covered these topics initially in his talk at Google's IO 2011. I highly recommend to watch the video of this talk. It's definitely a good watch!

相關推薦

Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime

BroadcastReceivers are good when you want to be notified about system events. But sometimes you do need to know about

Android Quick Tip: Formatting Text with Html.fromHtml()

Android offers you the possibility to easily format text with HTML markup. Thus it's easy to create text like this: S

Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux

Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and LinuxOne of programming’s little annoyances is that Microsoft Windows uses a b

更新 是 可用的 針對 安卓 軟件開發包和工具 Updates are available for android software development packages and tools

安卓 模擬器 軟件 ide software ava -m android 設置 作者:韓夢飛沙 Author:han_meng_fei_sha 郵箱:[email protected]/* */ E-mail: 313134555 @qq.com

Calculated and Aggregated Fields,Add Calculated field at runtime

tle file pre supports database pda ams tin chan http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Calculated_and_Aggregated_Fields_(FireD

Fix E: Could not get lock /var/cache/apt/archives/lock [Quick Tip]

Problem: The other day a reader asked me that she had troubles with this kind of error: E: Could not get lock /var/cache/apt/archives/lo

Android App To Record And Share Your Important Thoughts

Today, am happy to introduce to you my newest android application : Quotes! In a nutshell, this android app helps you record your deepest, perhaps mos

Win a Free Android Tablet For Developing and Testing Apps

Win a FREE android 7 inch tablet and use it to test your android applications before publishing them! Yeah, I am not kidding here pal, you could be a wi

How to distribute your own Android library through jCenter and Maven Central from Android Studio

In Android Studio, if you wish to include any library to your application. You could just simply add a following line of dependency in mo

Mirror android phone's screen and gain full control on computer with Vysor

Looking for a tool that could mirror non-rooted android phone's screen and allow user to gain a full control on computer? Here is a good

Some Thoughts on Android's new ConstraintLayout and Android Studio's new Design Editor

At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped la

Airbnb Engineering and Data Science at KDD 2018

The 2018 KDD conference is right around the corner — and we are looking forward to seeing you there. (That’s Knowledge Discovery and Data Mining, if you’re

Superset: Scaling Data Access and Visual Insights at Airbnb

Superset: Scaling Data Access and Visual Insights at AirbnbIntroductionAt Airbnb, one of our fundamental beliefs is that data access should be democratized

John de Monchaux, former dean of the School of Architecture and Planning, dies at 81

Jean Pierre de Monchaux, an idealistic and optimistic planner and architect who served as dean of the MIT School of Architecture and Planning from 1981 to

Ying Lee, longtime mechanical engineering professor, inventor, and entrepreneur, dies at 100 | MIT News

Shih-Ying Lee, a longtime MIT mechanical engineering professor and expert in process control, measurement, and instrumentation, passed away peacefully on J

Your Guide to AI and Machine Learning at re:Invent 2018

re:Invent 2018 is almost here! As you plan your agenda, artificial intelligence (AI) is undoubtedly a hot topic on your list. This year w

Make an android custom view, publish and open source.

Publish your library:After finish pushing your project to GitHub, there is the last step to get done: publish it so that developers can just add dependency

Quick Tip: create GIFs of your apps

[tl;dr: go to the GIF up your videos section]You’ll certainly have felt the need to show off some animation in your app, at some point. I mean, this is som

AWS Big Data and Analytics Sessions at Re:Invent 2018

re:Invent 2018 is around the corner! This year, data and analytics tracks are bigger than ever. This blog post highlights the data and ana

Kotlin for Android (III): Extension functions and default values

Now that you know the basics about Kotlin and how to configure your project, it´s time to talk about some interesting things that Kotlin can do for u