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

时间:2018-01-25 08:27:49

标签: 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.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);

1 个答案:

答案 0 :(得分:7)

问题在于Intent.CreateChooser又创建了另一个Intent。你想要做的是在这个新意图上设置标志:

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);
    var intent = Intent.CreateChooser(sharingInt, "Share via");
    intent.AddFlags(ActivityFlags.NewTask);
    context.StartActivity(intent);
}

或者为了避免这样做,你可以缓存MainActivity实例Xamarin.Forms使用:

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

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

然后在代码中使用Instance作为Context而不是Application.Context