Hi Geeks,
I have a requirement where I need to work in the following scenario.
When any user gets a call, identify the number, and launch my app in the background and insert a record in some table.
I searched through different forums and found BroadcastReceiver is the one by which I can get the incoming number.
However, I tried to implement this, but no success.
[BroadcastReceiver(Enabled =true)] [IntentFilter(new[] { "com.App.CALLER_RECEIVER" })] public class IncomingCallReader : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) { switch (intent.Action) { case Intent.ActionNewOutgoingCall: Globals.ContactNumber = intent.GetStringExtra(Intent.ExtraPhoneNumber); 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; } } protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xam.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); RegisterReceiver(new IncomingCallReader(), new IntentFilter("com.uniconta.mobile_new.app")); LoadApplication(new App()); }
Second Approach:
public interface ICallReceiver { void OnReceive(); } public class IncomingCallReceiver: ICallReceiver { public void OnReceive() { Intent intent = new Intent("com.uniconta.CALLER_RECEIVER"); var incomingPhoneNumber = intent.GetStringExtra(TelephonyManager.ExtraIncomingNumber); Globals.ContactNumber = incomingPhoneNumber; Forms.Context.SendBroadcast(intent); } }
DependencyService.Get().OnReceive();
I want this method to be called whenever the user gets a call.
1st question - Is it possible to get the incoming call number in Xamarin forms?
2nd Question - is it possible to launch an app in the background when someone gets a call and app can do things in the background?
Thanks
Anand