今天的程序可以实现电话状态改变时启动(来电、接听、挂断、拨打电话),但是暂时没法实现拨打电话时判断对方是否接听、转语音信箱等。Android在电话状态改变是会发送action为android.intent.action.PHONE_STATE的广播,而拨打电话时会发送action为android.intent.action.NEW_OUTGOING_CALL的广播,但是我看了下开发文档,暂时没发现有来电时的广播。知道这个就好办了,我们写个BroadcastReceiver用于接收这两个广播就可以了。
[java] view
plaincopy
-
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 {
-
-
@Override
-
public void onReceive(Context context, Intent intent) {
-
-
System.out.println("action"+intent.getAction());
-
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
-
-
System.out.println("拨出");
-
}else{
-
-
System.out.println("来电");
-
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
-
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
-
-
}
-
}
-
PhoneStateListener listener=new PhoneStateListener(){
-
-
@Override
-
public void onCallStateChanged(int state, String incomingNumber) {
-
-
-
super.onCallStateChanged(state, incomingNumber);
-
switch(state){
-
case TelephonyManager.CALL_STATE_IDLE:
-
System.out.println("挂断");
-
break;
-
case TelephonyManager.CALL_STATE_OFFHOOK:
-
System.out.println("接听");
-
break;
-
case TelephonyManager.CALL_STATE_RINGING:
-
System.out.println("响铃:来电号码"+incomingNumber);
-
-
break;
-
}
-
}
-
-
};
-
}
要在AndroidManifest.xml注册广播接收器:
[html] view
plaincopy
-
<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>
还要添加权限:
[html] view
plaincopy
-
<uses-permission android:name="android.permission.READ_PHONE_STATE">uses-permission>
-
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS">uses-permission>
转自 :http://www.pocketdigi.com/20110725/417.html