有时候我们开发软件的时候,需要拿到手机当前是否在通话状态,以做相应的处理。这时候就必然要去检测当前是否正在通话中。
先说说我们一般的做法:
1,在AndroidManifest.xml文件中,添加相应的权限和注册相应的广播接收。如下:
- <uses-permission android:name="android.permission.CALL_PHONE" />
- <uses-permission android:name="android.permission.CALL_PRIVILEGED" />
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />
- <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
- <!-- 拨打电话 -->
- <receiver android:name=".broadcast.PhoneStatReceiver">
- <intent-filter>
- <action android:name="android.intent.action.PHONE_STATE" />
- <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
- </intent-filter>
- </receiver>
<!-- 拨打电话 -->
<receiver android:name=".broadcast.PhoneStatReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
2,然后我们写个广播接收类去接收系统消息并做相应处理。如下:
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
- Log.e("hg", "呼出……OUTING");
- }
- if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
- TelephonyManager tm = (TelephonyManager) context
- .getSystemService(Service.TELEPHONY_SERVICE);
- switch (tm.getCallState()) {
- case TelephonyManager.CALL_STATE_RINGING:
- Log.e("hg", "电话状态……RINGING");
- break;
- case TelephonyManager.CALL_STATE_OFFHOOK:
- Log.e("hg", "电话状态……OFFHOOK");
- break;
- case TelephonyManager.CALL_STATE_IDLE:
- Log.e("hg", "电话状态……IDLE");
- break;
- }
- }
- }
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
Log.e("hg", "呼出……OUTING");
}
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
Log.e("hg", "电话状态……RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.e("hg", "电话状态……OFFHOOK");
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.e("hg", "电话状态……IDLE");
break;
}
}
}
3,将程序跑起来。看打印我们就能看到的调用顺序(当然了,我们也可以将上面的接收用两个类分开。这里我只是举个例子而已)
A:拨打15221XXXX好友,没接通前立马挂电话。State执行顺序:OFFHOOK---->IDLE
B:拨打15221XXXX好友,等着对方接通电话后。State执行顺序:OFFHOOK---->IDLE
C:好友打进来,自己不接,也不主动挂断。State执行顺序:RINGING---->IDLE
D:好友打进来,自己主动挂断或者好友主动挂断。State执行顺序:RINGING---->IDLE
E:好友打进来,我接。State执行顺序:RINGING---->OFFHOOK---->IDLE