Package COM. pocketdigi. phonelistener; import android. app. service; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. telephony. phonestatelistener; import android. telephony. telephonymanager; public class phonereceiver extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {// todo auto-generated method stubsystem. out. println ("action" + intent. getaction (); If (intent. getaction (). equals (intent. action_new_outgoing_call) {// if it is a power-off (outbound) system. out. println ("");} else {// check the android document. It seems that there is no action specifically used to receive incoming calls. out. println ("Incoming call"); telephonymanager TM = (telephonymanager) context. getsystemservice (service. telephony_service); TM. listen (listener, phonestatelistener. listen_call_state); // set a listener} phonestatelistener listener = new phonestatelistener () {@ overridepublic void oncallstatechanged (INT state, string incomingnumber) {// todo auto-generated method stub // state the incomingnumber in the current state. It seems that no apisuper is powered off. oncallstatechanged (State, incomingnumber); Switch (state) {Case telephonymanager. call_state_idle: system. out. println ("hanging up"); break; Case telephonymanager. call_state_offhook: system. out. println ("Answer"); break; Case telephonymanager. call_state_ringing: system. out. println ("Bell: Incoming call number" + incomingnumber); // outputs the incoming call number break ;}}};}
To register a broadcast receiver in androidmanifest. xml:
123456 |
<receiver android:name=".PhoneReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"/><action android:name="android.intent.action.NEW_OUTGOING_CALL" /> </intent-filter> </receiver> |
Also add permissions:
12 |
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission> |
<