Skip to content Skip to sidebar Skip to footer

Getting Phone State In Xamarin

I have following code: public class StateListener : PhoneStateListener { StateListener phoneStateListener = new StateListener(); TelephonyManager telephonyManag

Solution 1:

You have to move the creation code into the OnCreate method of your Activity.

protectedoverridevoidOnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    StateListener phoneStateListener = new StateListener();
    TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(Context.TelephonyService);
    telephonyManager.Listen(phoneStateListener, PhoneStateListenerFlags.CallState);
}

And then you can create the class:

publicclassStateListener : PhoneStateListener
{
    publicoverridevoidOnCallStateChanged(CallState state, string incomingNumber)
    {
        base.OnCallStateChanged(state, incomingNumber);
        switch (state)
        {
            case CallState.Ringing:
                break;
            case CallState.Offhook:
                break;
            case CallState.Idle:
                break;
        }
    }
}

If you want to do something on you activity after OnCallStateChanged you have to pass the activity (e.g. in the constructor):

publicclassStateListener : PhoneStateListener
{
    privatereadonly MainActivity _activity;

    publicStateListener(MainActivity activity)
    {
        _activity = activity;
    }

    publicoverridevoidOnCallStateChanged(CallState state, string incomingNumber)
    {
        base.OnCallStateChanged(state, incomingNumber);
        _activity.UpdateCallState(state, incomingNumber);
    }
}

publicclassMainActivity : Activity
{
    protectedoverridevoidOnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        StateListener phoneStateListener = new StateListener(this);
        TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(Context.TelephonyService);
        telephonyManager.Listen(phoneStateListener, PhoneStateListenerFlags.CallState);
    }

    publicvoidUpdateCallState(CallState state, string incomingNumber)
    {
        // numberLabel.Text = ...
    }
}

Post a Comment for "Getting Phone State In Xamarin"