一、添加监听电话状态所需权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
二、接受电话状态的广播
public class PhoneStateReceiver extends BroadcastReceiver {
private static final String TAG = "PhoneStateReceiver";
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive()");
String action = intent.getAction();
if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String outNumber = this.getResultData();
} else if ("android.intent.action.PHONE_STATE".equals(action)) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String inNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
} else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
} else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
}
}
}
}
三、在AndroidManifest.xml,配置写好的Receiver:
<receiver android:name=".PhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
|