Class myphonestatelistener extends phonestatelistener {
@ Override
Public void oncallstatechanged (INT state, string incomingnumber ){
Switch (state ){
Case telephonymanager. call_state_idle: // idle
Break;
Case telephonymanager. call_state_ringing: // incoming call
Break;
Case telephonymanager. call_state_offhook: // disconnect (in call)
Break;
}
}
}
// Obtain the telephone communication service
Telephonymanager TPM = (telephonymanager) This
. Getsystemservice (context. telephony_service );
// Create a listener to listen to the call status change event
TPM. Listen (New myphonestatelistener (),
Phonestatelistener. listen_call_state );
Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
The following article is reproduced from: http://www.eoeandroid.com/thread-8994-1-1.html
To listen for Android phone calls and answer calls, follow these steps:
Step 1: Write a receiver inherited from broadcastreceiver
Call action is telephonymanager. action_phone_state_changed
The power-off action is intent. action_new_outgoing_call.
Public class phonestatreceiver extends broadcastreceiver {
Private Static final string tag = "phonestatreceiver ";
// Private Static myphonestatelistener phonelistener = new myphonestatelistener ();
Private Static Boolean incomingflag = false;
Private Static string incoming_number = NULL;
@ Override
Public void onreceive (context, intent ){
// If you call
If (intent. getaction (). Equals (intent. action_new_outgoing_call )){
Incomingflag = false;
String phonenumber = intent. getstringextra (intent. extra_phone_number );
Log. I (TAG, "Call out:" + phonenumber );
} Else {
// For incoming calls
Telephonymanager TM =
(Telephonymanager) Context. getsystemservice (service. telephony_service );
Switch (TM. getcallstate ()){
Case telephonymanager. call_state_ringing:
Incomingflag = true; // identifies the current incoming call
Incoming_number = intent. getstringextra ("incoming_number ");
Log. I (TAG, "ringing:" + incoming_number );
Break;
Case telephonymanager. call_state_offhook:
If (incomingflag ){
Log. I (TAG, "Incoming accept:" + incoming_number );
}
Break;
Case telephonymanager. call_state_idle:
If (incomingflag ){
Log. I (TAG, "Incoming idle ");
}
Break;
}
}
}
}
Step 2: configure the receiver in androidmanifest. xml and intercept the corresponding broadcastaction,
In addition, add the corresponding permissions.
<receiver android:name=".filter.PhoneStatReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>