Share via


how to send data from Broadcast receiver to the activity

Question

Tuesday, October 2, 2018 6:40 PM

how to send data from Broadcast receiver to the activity

All replies (1)

Wednesday, October 3, 2018 8:56 AM

@farhad9999

You could try to create an Intent in your broadcast receiver, put your data in it and use StartActivity() to pass data. For example:

    public override void OnReceive(Context context, Intent intent)
    {
        string value = intent.GetStringExtra("key");
        Intent Newintent = new Intent(context, typeof(MainActivity));
        Newintent.PutExtra("value", value);
        context.StartActivity(Newintent);
    }

Or you could install Xamarin.Forms package from nuget. And using it MessagingCenter. For example, subscribe it in OnCreate():

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        MessagingCenter.Subscribe<SampleReceiver, Intent>(this, "Boardcast", (sender, arg) => {
            // do something
        });
    }

And the Send() in broadcast receiver:

    public override void OnReceive(Context context, Intent intent)
    {       
        string value = intent.GetStringExtra("key");     
        MessagingCenter.Send<SampleReceiver, Intent>(this, "Boardcast", intent);
    }