Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.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# 在Xamarin表单中传递上下文依赖项_C#_Xamarin_Xamarin.forms_Xamarin.android - Fatal编程技术网

C# 在Xamarin表单中传递上下文依赖项

C# 在Xamarin表单中传递上下文依赖项,c#,xamarin,xamarin.forms,xamarin.android,C#,Xamarin,Xamarin.forms,Xamarin.android,我在Xamarin.android中有一个类,我想从Xamarin表单页面调用该类,但问题是该类需要一个上下文,如何传递上下文? 在下面的链接中有关于此的信息,但不适用于我,在AlertDialog中始终会出现一个例外,链接: 下面是我需要调用的类: public class AlowApp { public static void StartPowerSaverIntent(Context context) { ISharedPreferences settin

我在Xamarin.android中有一个类,我想从Xamarin表单页面调用该类,但问题是该类需要一个上下文,如何传递上下文? 在下面的链接中有关于此的信息,但不适用于我,在AlertDialog中始终会出现一个例外,链接:

下面是我需要调用的类:

public class AlowApp
{
    public static void StartPowerSaverIntent(Context context)
    {
        ISharedPreferences settings = context.GetSharedPreferences("ProtectedApps", FileCreationMode.Private);
        bool skipMessage = settings.GetBoolean("skipAppListMessage", false);
        if (!skipMessage)
        {
            ISharedPreferencesEditor editor = settings.Edit();
            foreach (Intent intent in POWERMANAGER_INTENTS)
            {
                //                     if (context.PackageManager.ResolveActivity(intent, PackageInfoFlags.MatchDefaultOnly) != null)
                //                        {

                var giftimage = new WebView(context);

                giftimage.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
                giftimage.Settings.SetLayoutAlgorithm(WebSettings.LayoutAlgorithm.SingleColumn);
                giftimage.Settings.DomStorageEnabled = true;
                giftimage.Settings.CacheMode = CacheModes.NoCache;
                giftimage.Settings.LoadWithOverviewMode = true;
                giftimage.Settings.LoadsImagesAutomatically = true;
                giftimage.Settings.JavaScriptEnabled = true;
                giftimage.Settings.BuiltInZoomControls = false;
                giftimage.Settings.UseWideViewPort = true;
                giftimage.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
                giftimage.ScrollbarFadingEnabled = true;
                giftimage.Settings.JavaScriptEnabled = true;

                giftimage.SetBackgroundColor(Android.Graphics.Color.White);
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
                {
                    giftimage.SetLayerType(LayerType.Hardware, null);
                }
                else
                {
                    giftimage.SetLayerType(LayerType.Software, null);
                }

                giftimage.LoadUrl("file:///android_asset/sapo.gif");

                String titleText = "Notifications";
                SpannableStringBuilder ssbuilder = new SpannableStringBuilder(titleText);
                RelativeSizeSpan largeSizeText = new RelativeSizeSpan(0.8f);

                ssbuilder.SetSpan(
                    largeSizeText, // Span to add
                    0, // Start of the span
                    titleText.Length, // End of the span
                    SpanTypes.ExclusiveExclusive // Do not extent the span when text add later
                );

                String messageText = "Follow the instructions of the picture below.\n";
                SpannableStringBuilder ssbuildermsg = new SpannableStringBuilder(messageText);
                RelativeSizeSpan largeSizeTextmsg = new RelativeSizeSpan(0.9f);

                ssbuildermsg.SetSpan(
                    largeSizeTextmsg, // Span to add
                    0, // Start of the span
                    messageText.Length, // End of the span
                    SpanTypes.ExclusiveExclusive // Do not extent the span when text add later
                );

                new AlertDialog.Builder(context)
                    .SetIcon(Android.Resource.Drawable.IcDialogAlert)
                    .SetTitle(ssbuilder)
                    .SetMessage(ssbuildermsg)
                    .SetView(giftimage)
                    .SetPositiveButton("Next", (o, d) =>
                    {
                        try
                        {
                            context.StartActivity(intent);
                            editor.PutBoolean("skipAppListMessage", true);
                            editor.Apply();
                        }
                        catch (Exception e)
                        {
                            Toast.MakeText(context, "Not possible to go to definitions", ToastLength.Long).Show();
                        }

                    })
                    .SetNegativeButton("Cancel", (o, d) =>
                    {
                        editor.PutBoolean("skipAppListMessage", true);
                        editor.Apply();
                    })
                    .Show();

                break;
            }
            //                    }
        }
    }

    private static List<Intent> POWERMANAGER_INTENTS = new List<Intent>()
    {

        new Intent().SetComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
        new Intent().SetComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
        new Intent().SetComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
        new Intent().SetComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
        new Intent().SetComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
        new Intent().SetComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
        new Intent().SetComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
        new Intent().SetComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")).SetData(Android.Net.Uri.Parse("mobilemanager://function/entry/AutoStart"))
    };

}

在单个活动应用程序中,您只能在Xamarin.Forms 2.5或更高版本中使用Xamarin.Forms.Forms.Context

或者,如果需要跟踪当前上下文,可以使用如下类

[Application]
public partial class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
   internal static Context ActivityContext { get; private set; }

   public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }

   public override void OnCreate()
   {
      base.OnCreate();
      RegisterActivityLifecycleCallbacks(this);
   }    

   public override void OnTerminate()
   {
      base.OnTerminate();
      UnregisterActivityLifecycleCallbacks(this);
   }  

   public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
   {
      ActivityContext = activity;
   }   

   public void OnActivityResumed(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityStarted(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityDestroyed(Activity activity) { }  
   public void OnActivityPaused(Activity activity) { }
   public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
   public void OnActivityStopped(Activity activity) { }
}
范例


这门课怎么称呼?你有什么例外?试着用这个来获取上下文,它真的应该可以工作:Android.App.Application.context现在我只是从MainActivity调用,没有传递上下文,就像这样:AlowApp.startpowersavirecontent;使用Android.App.Application.Context会产生与以前相同的异常:未处理的异常:Android.Views.WindowManagerBadTokenException:无法添加窗口-应用程序不使用null标记
 StartPowerSaverIntent(MainApplication.ActivityContext)