Working with the Telephony Manager

The telephony APIs also include the telephony manager (android.telephony.TelephonyManager), which you can use to obtain information about the telephony services on the device, get subscriber information, and register for telephony state changes. A common telephony use case requires that an application execute business logic upon incoming phone calls. So in this section, we are going to show you how to register for telephony state changes and how to detect incoming phone calls. Listing 9-9 shows the details.

Listing 9-9. Using the Telephony Manager public class TelephonyServiceDemo extends Activity {

private static final String TAG="TelephonyServiceDemo"; ^Override protected void onCreate(Bundle savedInstanceState) {


TelephonyManager teleMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); teleMgr.listen(new MyPhoneStateListener(),

PhoneStateListener.LISTEN_CALL_STATE); }

class MyPhoneStateListener extends PhoneStateListener {

^Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber);

switch(state) {

incomingNumber+ incomingNumber+ incomingNumber+

incomingNumber+ }

When working with the telephony manager, be sure to add the <uses-permission android:name="android.permission.READ_PHONE_STATE" /> permission to your manifest file so you can access phone-state information. As shown in Listing 9-9, you get notified about phone-state changes by implementing a PhoneStateListener and calling the listen() method of the TelephonyManager. When a phone call arrives, or the phone state changes, the system will call your PhoneStateListener's onCallStateChanged() method with the new state and the incoming phone number. In the case of an incoming call, you look for the CALL_STATE_RINGING state. You write a debug message to the log file in this example, but your application could implement custom business logic in its place. To emulate incoming phone calls, you can use Eclipse's Emulator Control UI, as you did with SMS messages (see Figure 9-8).

When dealing with phone-state changes, you might also need to get the subscriber's (user's) phone number. TelephonyManager.getLine1Number() will return that for you.

0 0

Post a comment