我有一个要求,其中我想要检测与Android中的呼叫相关的两种事件
这在Android中可行吗?
答案 0 :(得分:29)
你应该创建一个BroadcastReceiver:
public class CallReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
// Phone number
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
// Ringing state
// This code will execute when the phone has an incoming call
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// This code will execute when the call is answered or disconnected
}
}
}
您应该注册您的应用程序以在清单中收听这些意图:
<receiver android:name=".CallReciever" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
答案 1 :(得分:7)
有一个更简单的解决方案,只使用TelephonyManager和 PhoneStateListener。您甚至不必注册BroadcastReceiver。
public class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//Hangup
case TelephonyManager.CALL_STATE_IDLE:
break;
//Outgoing
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
//Incoming
case TelephonyManager.CALL_STATE_RINGING:
break;
}
}
}
并注册:
public static void registerListener(Context context) {
((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).listen(new MyPhoneStateListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
答案 2 :(得分:4)
您需要为以下意图操作创建接收器: