How to handle the result of StartActivityForResult in Forms

In the Android specific code of my Xamarin.Forms project, I use the following code to request the user to turn Bluetooth on:

const int RequestEnableBt = 2;
var context = Forms.Context;
var activity = (Activity)context;
var intent = new Intent(BluetoothAdapter.ActionRequestEnable);
activity.StartActivityForResult(intent, RequestEnableBt);

The user can either accept or deny the request.
In Xamarin.Android the result is handled in Activity.OnActivityResult().
Is there a way to handle this in Xamarin.Forms?

Posts

  • AntaoAlmadaAntaoAlmada PTMember ✭✭

    It works! Thanks a lot for the tip.

  • manishchoudharymanishchoudhary USMember ✭✭

    Thanks @MarkFeldman

  • Richard_WRichard_W USMember ✭✭

    This was very helpful, and it works perfectly. Couple of things worth adding, for anyone starting out. I needed to use

    context.StartActivity(Intent.CreateChooser(intent, "Suitable title"));  
    

    instead of just passing the intent in directly. Also, to access the MainActivity context, I needed to save that as a static member in the MainActivity class, like this:

        internal static MainActivity Instance { get; private set; }
    
        protected override void OnCreate(Bundle bundle)
        {
             Instance = this;   
        ...
    }
    

    the Instance can then be used as either Context or cast to an Activity:

    Context context = MainActivity.Instance;
    MainActivity activity = (MainActivity)context;
    

    The only other thing is, for anyone who doesn't understand how to inject this into their shared code, is that you need to decorate the platform project namespace with

    [assembly: Xamarin.Forms.Dependency(typeof(BluetoothService))], 
    

    and in the PCL you will need to get an instance of the BluetoothService class like this:

    BluetoothService service = DependencyService.Get<IBluetoothService>();
    

    But this really shows just how easy it is to call a platform method from the PCL.

Sign In or Register to comment.