user3165999
user3165999

Reputation: 159

How to get intent activity result in xamarin forms

I am trying to use dependency service to initiate intent for enabling BT in my xamarin forms app. But Iam finding difficulty in getting result back to xamarin forms. Is there any mechanism to get activityresult notification back to forms app. In forms,

DependencyService.Get<IBluetoothHandler>().EnableBluetooth();

In android,

Activity activity = Forms.Context as Activity;
Intent intent = new Intent(BluetoothAdapter.ActionRequestEnable);
activity.StartActivityForResult(intent, 1);

How can i get this activity result to forms?

Thanks

Upvotes: 2

Views: 6375

Answers (2)

Abdullah Tahan
Abdullah Tahan

Reputation: 2139

in MainActivity add this

public static MainActivity Instance;

and in OnCreate method add :

 Instance = this;

Upvotes: 2

Joehl
Joehl

Reputation: 3701

You can override the OnActivityResult method in your MainActivity in your android project. Xamarin.Forms uses just one activity for the whole app (behind the scenes). So just use this one.

To inform your page (or just another class in your PCL/Forms project) use the messagingcenter provided by Xamarin.Forms.

Here's an example:

Your method in your MainActicity (android project):

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    // Send trough the messaging sender (maybe someone subscribes to it)
    MessagingCenter.Send(
        new ActivityResultMessage {RequestCode = requestCode, ResultCode = resultCode, Data = data}, ActivityResultMessage.Key);
}

Then your messaging class:

public class ActivityResultMessage
{
    public static string Key = "arm";

    public int RequestCode { get; set; }

    public object ResultCode { get; set; }

    public object Data { get; set; }
}

And then use the following code in the class to handle the result:

// Subscribe to the onactivityresult-message
MessagingCenter.Subscribe<ActivityResultMessage>(this, ActivityResultMessage.Key, (sender) =>
{
    // do some magic =)
});

Please read the stuff about the messagincenter (link provided above), to understand the things behind.

Upvotes: 2

Related Questions