demo1(通用):
权限
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
注册:
<receiver android:name=".PhoneReceiver"><intent-filter android:priority="1000"><action android:name="android.intent.action.NEW_OUTGOING_CALL" /><action android:name="android.intent.action.PHONE_STATE" /></intent-filter>
</receiver>
声明:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;public class PhoneReceiver extends BroadcastReceiver {private static final String TAG = PhoneReceiver.class.getSimpleName();@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);String outNumber = this.getResultData();Log.i(TAG, "call OUT 1:" + phoneNumber);Log.i(TAG, "call OUT 2:" + outNumber);} else if ("android.intent.action.PHONE_STATE".equals(intent.getAction())) {TelephonyManager tManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);String mIncomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);Log.i(TAG, "call IN 1:" + state);Log.i(TAG, "call IN 2:" + mIncomingNumber);switch (tManager.getCallState()) {case TelephonyManager.CALL_STATE_RINGING:Log.d(TAG, "**********************监测到电话呼入!!!!*****");break;case TelephonyManager.CALL_STATE_OFFHOOK:Log.d(TAG, "**********************监测到接听电话!!!!************");break;case TelephonyManager.CALL_STATE_IDLE:Log.d(TAG, "**********************监测到挂断电话!!!!*******************");break;}}}
}
demo2 :
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
private class MyPhoneStateListener extends PhoneStateListener {@Overridepublic void onCallStateChanged(int state, String phoneNumber) {super.onCallStateChanged(state, phoneNumber);switch (state) {case TelephonyManager.CALL_STATE_IDLE:Log.d(TAG, "**********************监测到挂断电话!!!!*******************");break;case TelephonyManager.CALL_STATE_OFFHOOK://接听状态Log.d(TAG, "**********************监测到接听电话!!!!************");break;case TelephonyManager.CALL_STATE_RINGING://电话响铃状态Log.d(TAG, "**********************监测到电话呼入!!!!*****");break;default:break;}}
}