获取当前活动 - Xamarin Android [英] Get current Activity - Xamarin Android
问题描述
我正在开发适用于 Android 和 iOS 的便携式应用程序.我当前的功能是截取屏幕截图并在代码中使用该图像.因此,我在便携式库中有一个接口.
I am developing an portable App for Android and iOS. My current function is taking a Screenshot and use that image in the code. Therefor I have an Interface in the portable library.
public interface IFileSystemService
{
string GetAppDataFolder();
}
我也在便携式库中使用以下代码截取屏幕截图:
I am taking 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;
}
这要么调用Android 要么调用iOS 版本.
This either calls the Android or the iOS version.
安卓:
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;
}
现在的问题是从我的应用中获取当前的 Activity.
The question now is to get the current Activity from my app.
推荐答案
自 Xamarin 2.5 发布以来,Xamarin.Forms.Forms.Context 是 过时.现在可以通过以下方式获取上下文:
Since the release of Xamarin 2.5, Xamarin.Forms.Forms.Context is obsolete. The Context can now be obtained as follows:
var currentContext = Android.App.Application.Context;
这篇关于获取当前活动 - Xamarin Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!