Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试拍摄屏幕快照时,“活动”为空_C#_Xamarin.forms - Fatal编程技术网

C# 尝试拍摄屏幕快照时,“活动”为空

C# 尝试拍摄屏幕快照时,“活动”为空,c#,xamarin.forms,C#,Xamarin.forms,我的项目类型是xamarin表单中的PCL。我想截图,我使用下面的代码。但是当我调试代码时,我的活动总是空的。我正试图解决这个问题,但没有成功。你能告诉我我犯了什么错误吗 public interface IScreenshotManager { Task<byte[]> CaptureAsync(); } 对于Android: [assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService))] namespace

我的项目类型是xamarin表单中的PCL。我想截图,我使用下面的代码。但是当我调试代码时,我的活动总是空的。我正试图解决这个问题,但没有成功。你能告诉我我犯了什么错误吗

public interface IScreenshotManager
{
   Task<byte[]> CaptureAsync();
}
对于Android:

[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService))]
namespace MyProject.Droid
{
    public class ScreenshotService : IScreenshotService
    {
        public static Activity Activity { get; set; }               

        public async System.Threading.Tasks.Task<byte[]> Capture()
        {
            if (Activity == null)  // Activity is always null Error here
            {
                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;
        }
    }

}
调用函数

 byte[] screenshotData = await DependencyService.Get<IScreenshotService>().Capture();

显然,如果不分配活动,则该活动为空。您可以使用CurrentActivity nuget包获取当前活动,也可以在activity OnCreate方法中分配它,因为Xamarin从一开始就始终使用相同的活动。

旧的不推荐方式是var view=ActivityXamarin.Forms.Forms.Context.Window.DecorView; Xamarin会自动将活动分配给Forms.Context。自Xamarin 2.5发布以来,Xamarin.Forms.Forms.Context已过时

现在你可以用这个:

var currentContext = Android.App.Application.Context;

如何分配activity onCreate它应该是ScreenshotService。activity=this;