gpt4 book ai didi

c# - 获取当前 Activity - Xamarin Android

转载 作者:可可西里 更新时间:2023-11-01 18:49:29 25 4
gpt4 key购买 nike

我正在为 Android 和 iOS 开发一个可移植应用程序。我当前的功能是截取屏幕截图并在代码中使用该图像。因此,我在可移植库中有一个接口(interface)。

public interface IFileSystemService
{
string GetAppDataFolder();
}

我也在可移植库中使用以下代码截取屏幕截图:

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

这会调用 Android 或 iOS 版本。

安卓:

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 。

最佳答案

更好的方法是使用 Standalone Current Activity PluginXamarin Essentials Plugin 中的当前 Activity 属性.然后你可以这样做:

  • 独立:CrossCurrentActivity.Current.Activity
  • Xamarin Essentials:Platform.CurrentActivity

如果您不想使用插件并且您的应用中只有 1 个 Activity,您可以在 MainActivity 中分配一个静态变量并引用它在任何需要它的地方:

public class MainActivity : FormsApplicationActivity {
public static Context Context;

public MainActivity () {
Context = this;
}
}

如果您在自定义渲染器中需要 Context,您会希望使用传递给构造函数的 Context,如下所示:

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)
}

旧的弃用方式是 Context view = (Activity)Xamarin.Forms.Forms.Context

Xamarin 自动将 Activity 分配给 Forms.Context

关于c# - 获取当前 Activity - Xamarin Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43279971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com