当我接听电话时如何获得活动

时间:2017-05-29 06:53:29

标签: c# android xamarin xamarin.android

你能帮我理解如何检测是否接听来电(我需要记录从接听到接听的呼叫)?我可以检测到来电但不是外拨。所以请帮忙。

1 个答案:

答案 0 :(得分:1)

使用TelephonyManager.ActionPhoneStateChanged来监控TelephonyManager状态,一旦收到TelephonyManager.ExtraStateIdle,您就知道电话无线电现在处于空闲状态(没有正在通话中)。

入境&出站BroadcastReceiver示例:

[BroadcastReceiver(Name = "com.sushhangover.OutgoingCallBroadcastReceiver")]
[IntentFilter(new[] { Intent.ActionNewOutgoingCall, TelephonyManager.ActionPhoneStateChanged })]
public class OutgoingCallBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        switch (intent.Action)
        {
            case Intent.ActionNewOutgoingCall:
                var outboundPhoneNumber = intent.GetStringExtra(Intent.ExtraPhoneNumber);
                Toast.MakeText(context, $"Started: Outgoing Call to {outboundPhoneNumber}", ToastLength.Long).Show();
                break;
            case TelephonyManager.ActionPhoneStateChanged:
                var state = intent.GetStringExtra(TelephonyManager.ExtraState);
                if (state == TelephonyManager.ExtraStateIdle)
                    Toast.MakeText(context, "Phone Idle (call ended)", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraStateOffhook)
                    Toast.MakeText(context, "Phone Off Hook", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraStateRinging)
                    Toast.MakeText(context, "Phone Ringing", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraIncomingNumber)
                {
                    var incomingPhoneNumber = intent.GetStringExtra(TelephonyManager.ExtraIncomingNumber);
                    Toast.MakeText(context, $"Incoming Number: {incomingPhoneNumber}", ToastLength.Long).Show();
                }
                break;
            default:
                break;
        }
    }
}

注意:请确保您为ReadPhoneStateProcessOutgoingCalls添加权限,以便此示例正常运行。