How do I use TaskCompletionSource to return a result from a PendingIntent BroadcastReceiver?

primehaloprimehalo Member ✭✭

I've implemented a Dependency Service to send an SMS and am trying to return a result. I think I was able to figure out how to do this in iOS using a lamba expression for the Finished callback and setting the result of a TaskCompletionSource inside of that callback, but I can't figure out how to do this with Android's BroadcastReceiver.

public Task<SmsResult> SendSmsAsync(string to = null, string message = "")
{
    var tcs = new TaskCompletionSource<SmsResult>();

    _smsManager = SmsManager.Default;
    _smsSentBroadcastReceiver = new SMSSentReceiver();
    _smsDeliveredBroadcastReceiver = new SMSDeliveredReceiver();

    var piSent = Android.App.PendingIntent.GetBroadcast(Android.App.Application.Context, 0, new Intent(MY_SMS_SENT_INTENT_ACTION), 0);
    var piDelivered = Android.App.PendingIntent.GetBroadcast(Android.App.Application.Context, 0, new Intent(MY_SMS_DELIVERY_INTENT_ACTION), 0);

    Android.App.Application.Context.RegisterReceiver(_smsSentBroadcastReceiver, new IntentFilter(MY_SMS_SENT_INTENT_ACTION));
    Android.App.Application.Context.RegisterReceiver(_smsDeliveredBroadcastReceiver, new IntentFilter(MY_SMS_DELIVERY_INTENT_ACTION));

    _smsManager.SendTextMessage(to, from, message, piSent, piDelivered);
    return tcs.Task;
}

[BroadcastReceiver(Exported = true)]
public class SMSSentReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
    }
}

[BroadcastReceiver(Exported = true)]
public class SMSDeliveredReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
    }
}

How do I set the result of my TaskCompletionSource inside of the OnReceive()? If I move the TaskCompleteionSource declaration outside of my SendSmsAsync like so:

class MySms : IMySms
{
    private TaskCompletionSource<SmsResult> _tcs = new TaskCompletionSource<SmsResult>();
}

I still can't use this _tcs inside the BroadcaseReceiver because it says an object reference is required for the non-static field, method, or property 'MySms._tcs'.

Answers

  • robbitrobbit CNMember Xamurai

    Hi @primehalo

    Where is your SMSSentReceiver and SMSDeliveredReceiver? Inside your MySms?

    an object reference is required for the non-static field, method, or property 'MySms._tcs'.

    You can read this.

  • primehaloprimehalo Member ✭✭

    Yes, SMSSentReceiver and SMSDeliveredReceiver are both inside MySms. I ended up using MessagingCenter to accomplish this. Inside MySms I would generate a unique message that I could subscribe with MessagingCenter and then in SMSSentReceiver and SMSDeliveredReceiver I use MessagingCenter to send that same unique message along with the BroadcastReceiver result. There's probably a better way to do it but I needed to just get it working so I could move on.

Sign In or Register to comment.