Preface
In this article, we will learn to write code which responds to various phone events such as: phone ring, start conversation, start outgoing call, etc.
The implementation of this code is done by a class which extends the BroadcastReceiver
class, and overrides the onReceive
method:
public void onReceive(Context context, Intent intent)
This function is called when a certain phone event occurs.
Define Permissions
The Android operating system requires to explicitly specify permission for every action that involves operating various core events and components in the Android operating systems such as: handling phone events, accessing internet connectivity, operating the inner camera of the phone and so forth. We define these permissions in the AndroidManifest.xml file (in the root directory):
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Another thing we have to define in the AndroidManifest.xml file is an intent filter. An intent filter defines two things:
- That a specific class is defined as a
BroadCastReciever
class. - That this class will respond to certain phone events such as phone call, SMS receive.
This intent filter is defined in the AndroidManifest.xml inside the <Application>
element:
<receiver android:name=".MyPhoneReciever"/>
<intent-filter/>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
The BroadcastReciever Derived Class
As I explained before, we have to build a class which is derived from the BroadcastReciever
class. In that class, we override the onReceive
method:
public class MyPhoneReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String outgoingPhoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String incomingPhoneNumber =
intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (intent.getStringExtra
(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
}
if (intent.getStringExtra
(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
}
if (intent.getStringExtra
(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING))
{
}
Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
}
}
Conclusion
What I have described here is only a sample code which explained only the fundamentals of handling various phone events. To see a full featured program which records your phone calls (incoming and outgoing), click here.