Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

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

$
0
0

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'.


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>