Recipe 4.3 Monitoring Phone State in the Background

Android Versions
Level 1 and above
Permissions
android.permission.READ_PHONE_STATE
Source Code Download from Wrox.com
Phone.zip

The previous recipe showed you how to monitor your phone state using the PhoneStateListener class. However, if your application is not running, you will not be able to monitor for changes in phone state. A better way, therefore, is to declare a BroadcastReceiver object in the AndroidManifest.xml file; that way, as long as your application is installed on the device (even if the application is not running), you will be able to monitor for changes to the phone state.

Solution

To ensure that your application continues to monitor for changes to the phone state, you need to create a class that extends the BroadcastReceiver base class. Within this class, you create an inner class that implements the PhoneStateListener class (see the previous recipe for details on how it works). Then you override the onReceive() method of the BroadcastReceiver class so that you can call the listen() method of the TelephonyManager class to monitor for phone state changes using an instance of the PhoneStateListener class. You need to ensure that you do not register the listener more than once.

The following example shows how to code the steps just outlined:

package net.learn2develop.phone; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.PhoneStateListener; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.