Xamarin Android通过社交媒体从自定义渲染器共享链接/文本

Xamarin Android通过社交媒体从自定义渲染器共享链接/文本,xamarin,xamarin.forms,xamarin.android,Xamarin,Xamarin.forms,Xamarin.android,我不想通过社交媒体从自定义渲染器共享链接 public class CustomActions : ICustomActions { Context context = Android.App.Application.Context; public void ShareThisLink() { Intent sharingInt = new Intent(Android.Content.Intent.ActionS

我不想通过社交媒体从自定义渲染器共享链接

public class CustomActions : ICustomActions
    {
        Context context = Android.App.Application.Context;

        public void ShareThisLink()
        {
            Intent sharingInt = new Intent(Android.Content.Intent.ActionSend);
            sharingInt.SetType("text/plain");
            string shareBody = "https://www.google.com";
            sharingInt.PutExtra(Android.Content.Intent.ExtraSubject, "Subject");
            sharingInt.PutExtra(Android.Content.Intent.ExtraText, shareBody);
            context.StartActivity(Intent.CreateChooser(sharingInt, "Share via"));
        }

    }
发生此错误

Android.Util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
即使我添加了下面的代码,我仍然会得到相同的错误

 sharingInt.AddFlags(ActivityFlags.NewTask);

问题在于
Intent.CreateChooser
创建了另一个
Intent
。您要做的是设置此新意图的标志:

public void ShareThisLink()
{
意向共享=新意向(Android.Content.Intent.ActionSend);
sharingInt.SetType(“文本/普通”);
字符串共享体=”https://www.google.com";
sharingInt.PutExtra(Android.Content.Intent.ExtraSubject,“Subject”);
sharingInt.PutExtra(Android.Content.Intent.extextext,shareBody);
var intent=intent.CreateChooser(sharingInt,“通过共享”);
intent.AddFlags(ActivityFlags.NewTask);
背景。开始触觉(意图);
}
或者,为了避免这样做,您可以缓存
MainActivity
实例Xamarin。表单使用:

public MainActivity
{
   public static MainActivity Instance {get;private set;}

   protected override void OnCreate(Bundle bundle)
   {
       Instance = this;
       ...
   }
}

然后使用
实例
作为代码中的
上下文
,而不是
应用程序。上下文

非常感谢:-)!哇!你不仅为我的问题提供了解决方案,还提供了两个。这两种方法都有效,而背景问题对我来说是个大问题。谢谢你。@bobwki很高兴这有帮助:-)。快乐编码!