Get current Activity – Xamarin Android

A better way would be to use the Standalone Current Activity Plugin or the Current Activity Property in the Xamarin Essentials Plugin. Then you could just do:

  • Standalone: CrossCurrentActivity.Current.Activity
  • Xamarin Essentials: Platform.CurrentActivity

If you do not want to use a plugin and you only have 1 Activity in your app, you could get away with assigning a static variable in MainActivity and referencing that where ever you needed it like this:

public class MainActivity : FormsApplicationActivity {
    public static Context Context;

    public MainActivity () {
        Context = this;
    }
}

If you needed Context within a custom renderer, you would want to use the Context passed into the constructor, like this:

public class MyEntryRenderer : EntryRenderer {

    private readonly Context _context;

    public MyEntryRenderer(Context context) : base(context) {
        _context = context;
    }

    // Now use _context or ((Activity)_context) any where you need to (just make sure you pass it into the base constructor)
}

The old deprecated way would be Context view = (Activity)Xamarin.Forms.Forms.Context

Xamarin automatically assigns the Activity to Forms.Context.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)