Get Current Activity - Xamarin Android

I am developing a portable application for Android and iOS. My current function takes a screenshot and uses this image in code. Therefore, I have an interface in a portable library.

public interface IFileSystemService
{
    string GetAppDataFolder();
}

I take the screenshot also in the portable library with the following code:

static public bool TakeScreenshot()
    {
        try
        {
            byte[] ScreenshotBytes = DependencyService.Get<Interface.IScreenshotManager>().TakeScreenshot();
            return true;
        }
        catch (Exception ex)
        {
        }
        return false;
    }

This either calls the version of Android or iOS.

Android:

class ScreenshotManagerAndroid : IScreenshotManager
{
    public static Activity Activity { get; set; }

    public byte[] TakeScreenshot()
    {

        if (Activity == null)
        {
            throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
        }

        var view = Activity.Window.DecorView;
        view.DrawingCacheEnabled = true;

        Bitmap bitmap = view.GetDrawingCache(true);

        byte[] bitmapData;

        using (var stream = new MemoryStream())
        {
            bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
            bitmapData = stream.ToArray();
        }

        return bitmapData;
    }

The question now is to get the current activity from my application.

+4
source share
2 answers

Try to execute var view = ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView;

Xamarin automatically assigns Activity Forms.Context.

+7
source
var activity = (Activity)Forms.Context;

or if you use MainActivity

var activity = (MainActivity)Forms.Context;
+9

Source: https://habr.com/ru/post/1674312/


All Articles