在Xamarin表单中传递Context Dependency

时间:2018-04-24 09:04:51

标签: c# xamarin xamarin.forms xamarin.android

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

Accessing Android Application Context

这里需要调用的类:

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

}

1 个答案:

答案 0 :(得分:1)

在单个活动应用中,您可以在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) { }
}

示例

 StartPowerSaverIntent(MainApplication.ActivityContext)