Phill
Phill

Reputation: 427

Pass Context Dependency in Xamarin forms

I have a class in Xamarin.android and i want to call the class from a xamarin forms page, but the problem is that the class needs a Context, how can I pass the context? In the link below has information about this, but isnt working for me, in the AlertDialog always gives an exception, link:

Accessing Android Application Context

Here the class that I need to be called:

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

}

Upvotes: 0

Views: 1282

Answers (1)

TheGeneral
TheGeneral

Reputation: 81483

In a single activity app you can just use Xamarin.Forms.Forms.Context in Xamarin.Forms 2.5 or greater

or if you need to track the current context you could use a class like this

[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) { }
}

Example

 StartPowerSaverIntent(MainApplication.ActivityContext)

Upvotes: 1

Related Questions