public override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            HasOptionsMenu = true;

            if (bundle != null)
            {
                updateCiudades(bundle.GetStringArray("CIUDADES"), bundle.GetIntArray("LOGOS"), bundle.GetStringArray("INFO"));
            }
            // Create your fragment here
        }
Пример #2
0
        protected override void OnReceiveResult(int resultCode, Bundle resultData)
        {
            base.OnReceiveResult(resultCode, resultData);

            var permissions  = resultData.GetStringArray(PermissionsHelper.KeyPermissions);
            var grantResults = resultData.GetIntArray(PermissionsHelper.KeyGrants);

            var permissionState = permissions.Select((t, i) => new PermissionState(t, grantResults[i] == (int)Permission.Granted)).ToList();

            _tcs.SetResult(permissionState);
        }
Пример #3
0
 protected override void OnRestoreInstanceState(Bundle bundle)
 {
     RestoreDataFromStrArr(bundle.GetStringArray("TAGS_ARR"), bundle.GetStringArray("DATA_ARR"));
     resultTextView.Text = bundle.GetString("RESULT_TEXT");
     //after an orientation change, force user to enter scale again
     if (bundle.GetString("V_VIEW_HEIGHT") != vView.Height.ToString())                //iView.Visibility == true || vView.Visibility == true)
     {
         scaleButton.Enabled   = true;
         computeButton.Enabled = false;
     }
     /// I really need to make sure this isn't a dumb way to do things. :)
     Android.Net.Uri uri;
     try {
         uri = (Android.Net.Uri)bundle.GetParcelable("MEDIA_URI");
     } catch (Exception) {
         uri = null;
     }
     if (uri != null)
     {
         LoadMedia(uri);
     }
     base.OnRestoreInstanceState(bundle);
 }
        public void StringArray()
        {
            string[] dataIn = new string[] { "a", "bcd" };
            Intent   i      = new Intent();

            i.PutExtra("key", dataIn);

            Bundle extras  = i.Extras;
            var    dataOut = extras.GetStringArray("key");

            Assert.AreEqual(dataIn.Length, dataOut.Length);
            Assert.AreEqual(dataIn[0], dataOut[0]);
            Assert.AreEqual(dataIn[1], dataOut[1]);
        }
Пример #5
0
        public void ParseBundle(Bundle bundle)
        {
            if (bundle == null)
            {
                return;
            }
            CurrentPageIndex = bundle.GetInt("CurrentPageIndex");
            Site             = bundle.GetString("Site");
            //User Information
            User             = bundle.GetString("User");
            UserDesc         = bundle.GetString("UserDesc");
            EmpNum           = bundle.GetString("EmpNum");
            EmpName          = bundle.GetString("EmpName");
            Currency         = bundle.GetString("Currency");
            DefaultWarehouse = bundle.GetString("DefaultWarehouse");
            DefaultLocation  = bundle.GetString("DefaultLocation");
            QuantityFormat   = bundle.GetString("QuantityFormat");
            AmountFormat     = bundle.GetString("AmountFormat");

            //Login Configurations
            Token              = bundle.GetString("Token");
            Theme              = bundle.GetString("Theme");
            CSIWebServerName   = bundle.GetString("CSIWebServerName");
            EnableHTTPS        = bundle.GetBoolean("EnableHTTPS");
            Configuration      = bundle.GetString("Configuration");
            ConfigurationList  = new List <String>(bundle.GetStringArray("ConfigurationList"));
            RecordCap          = bundle.GetString("RecordCap");
            SaveUser           = bundle.GetBoolean("SaveUser");
            SavedUser          = bundle.GetString("SavedUser");
            SavePassword       = bundle.GetBoolean("SavePassword");
            SavedPassword      = bundle.GetString("SavedPassword");
            UseRESTForRequest  = bundle.GetBoolean("UseRESTForRequest");
            LoadPicture        = bundle.GetBoolean("LoadPicture");
            ForceAutoPost      = bundle.GetBoolean("ForceAutoPost");
            ShowSuccessMessage = bundle.GetBoolean("ShowSuccessMessage");
            DisplayWhenError   = bundle.GetBoolean("DisplayWhenError");

            //Passed Key Information
            Key         = bundle.GetString("Key");
            LineSuffix  = bundle.GetString("LineSuffix");
            Release     = bundle.GetString("Release");
            Key2        = bundle.GetString("Key2");
            LineSuffix2 = bundle.GetString("LineSuffix2");
            Release2    = bundle.GetString("Release2");

            //License
            LicenseString = bundle.GetString("LicenseString");
            ExpDate       = string.IsNullOrEmpty(bundle.GetString("ExpDate")) ? DateTime.Today.AddDays(30).ToShortDateString() : bundle.GetString("ExpDate");
        }
        protected override void OnResume()
        {
            base.OnResume();

            // If app restrictions are set for this package, when launched from a restricted profile,
            // the settings are available in the returned Bundle as key/value pairs.
            mRestrictionsBundle = ((UserManager)GetSystemService(Context.UserService))
                                  .GetApplicationRestrictions(PackageName);

            if (mRestrictionsBundle == null)
            {
                mRestrictionsBundle = new Bundle();
            }

            // Reads and displays values from a boolean type restriction entry, if available.
            // An app can utilize these settings to restrict its content under a restricted profile.
            String booleanRestrictionValue =
                mRestrictionsBundle.ContainsKey(GetRestrictionsReceiver.KEY_BOOLEAN) ?
                mRestrictionsBundle.GetBoolean(GetRestrictionsReceiver.KEY_BOOLEAN) + "":
                GetString(Resource.String.na);

            mBooleanEntryValue.Text = booleanRestrictionValue;

            // Reads and displays values from a single choice restriction entry, if available.
            String singleChoiceRestrictionValue =
                mRestrictionsBundle.ContainsKey(GetRestrictionsReceiver.KEY_CHOICE) ?
                mRestrictionsBundle.GetString(GetRestrictionsReceiver.KEY_CHOICE) :
                GetString(Resource.String.na);

            mChoiceEntryValue.Text = singleChoiceRestrictionValue;

            // Reads and displays values from a multi-select restriction entry, if available.
            String[] multiSelectValues =
                mRestrictionsBundle.GetStringArray(GetRestrictionsReceiver.KEY_MULTI_SELECT);

            if (multiSelectValues == null || multiSelectValues.Length == 0)
            {
                mMultiEntryValue.Text = GetString(Resource.String.na);
            }
            else
            {
                String tempValue = "";
                foreach (String value in multiSelectValues)
                {
                    tempValue = tempValue + value + " ";
                }
                mMultiEntryValue.Text = tempValue;
            }
        }
Пример #7
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.activity_choice);
            // get intent data
            //var intent = Intent.GetStringExtra("categoryname") ?? "Not available";

            Bundle b = Intent.Extras;

            // Set Activity Title with the selected category
            Title      = b.GetString("category");
            choiceList = b.GetStringArray("choices").ToList();
            detailList = b.GetStringArray("details").ToList();

            ArrayAdapter <String> arrayAdapter = new ArrayAdapter <String>(
                this,
                global::Android.Resource.Layout.SimpleListItem1,
                choiceList);

            listView            = (ListView)FindViewById <ListView>(Resource.Id.lvChoices);
            listView.Adapter    = arrayAdapter;
            listView.ItemClick += OnListItemClick;
        }
Пример #8
0
 public static void RestoreRoomsFromBundle(Bundle bundle)
 {
     if (bundle.Contains(ROOMS))
     {
         SPECIALS.Clear();
         foreach (var type in bundle.GetStringArray(ROOMS))
         {
             SPECIALS.Add((RoomType)Enum.Parse(typeof(RoomType), type));
         }
     }
     else
     {
         ShuffleTypes();
     }
 }
Пример #9
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            if (bundle != null)
            {
                dataStudent = bundle.GetStringArray("dataStudent");
            }

            Button button = FindViewById <Button>(Resource.Id.buttonValidate);

            button.Click += delegate
            {
                Validate();
            };
        }
Пример #10
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);
            View   view         = inflater.Inflate(Resource.Layout.PhoneVerification, container, true);
            Button verifyButton = view.FindViewById <Button>(Resource.Id.Verify);

            verifyButton.Click += VerifyButton_Click;
            if (savedInstanceState != null && savedInstanceState.ContainsKey(PRE_LOADED))
            {
                long     secondsLeft = savedInstanceState.GetLong(TIMER_COUNT);
                TextView textTimer   = view.FindViewById <TextView>(Resource.Id.countdownTimer);

                if (secondsLeft > 0)
                {
                    textTimer.Text = "00:" + secondsLeft.ToString();
                    Timer          = new VerificationCountDownTimer(textTimer, (int)secondsLeft, 1000);
                }
                else
                {
                    string[] formerValues = savedInstanceState.GetStringArray(INPUT_VALUES);
                    useTimer       = false;
                    textTimer.Text = "00:00";
                    ReadyInputs(formerValues);
                }
            }
            else
            {
                TextView textTimer = view.FindViewById <TextView>(Resource.Id.countdownTimer);
                textTimer.Text = "00:" + verificationTimeout.ToString();
                Timer          = new VerificationCountDownTimer(textTimer, verificationTimeout, 1000);
            }

            if (Dialog != null)
            {
                if (useTimer)
                {
                    Timer.FinishedCount += Timer_FinishedCount;
                    Timer.Start();
                }
            }
            return(view);
        }
Пример #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.listEvidence);

            dataStudent = Intent.GetStringArrayExtra("dataStudent");

            if (dataStudent != null)
            {
                if (savedInstanceState != null)
                {
                    dataStudent = savedInstanceState.GetStringArray("dataStudent");
                }

                FindViewById <TextView>(Resource.Id.tvFullName).Text = dataStudent[1];

                if (dataStudent != null && !string.IsNullOrEmpty(dataStudent[0]))
                {
                    GetEvidencesAsync();
                }
            }
        }
Пример #12
0
        private static List <Badge> Restore(Bundle bundle)
        {
            var badges = new List <Badge>();

            var names = bundle.GetStringArray(Badges);

            foreach (var name in names)
            {
                try
                {
                    //badges.Add(new Badge(

                    //    Enum.Parse = new Badge(typeof = new Badge(Badge), names[i])

                    //    );
                }
                catch (Exception)
                {
                }
            }

            return(badges);
        }
Пример #13
0
		public override View OnCreateView (LayoutInflater inflater, 
		                                   ViewGroup container, Bundle savedInstanceState)
		{
			// Use this to return your custom view for this Fragment
			// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
			var root = inflater.Inflate (Resource.Layout.add_show_gridview_layout, container, false);

			mGridView = root.FindViewById<GridView> (Resource.Id.myGridview);
			setUpAdapter ();

			string buttonText = "I am in position " + position + " with title " + title + " And value " + getGenreValue (title);

			if (savedInstanceState != null) {
				var myNewList = savedInstanceState.GetStringArray ("TrakkedList");
				if (myNewList != null) {
					//mAdapter.setTrakkedShows ((List<string>)savedInstanceState.GetStringArrayList ("TrakkedList"));
					buttonText += "" + myNewList.Length;
				}
			}

			Button b = root.FindViewById<Button> (Resource.Id.bRandomButton);
			b.Text = buttonText;
			b.Click += delegate(object sender, EventArgs e) {
				//mAdapter.NotifyDataSetChanged();
				//Toast.MakeText (this.Activity, "Length of adapter array is "+mAdapter.sizeOfMyShows(), ToastLength.Short).Show ();
				setUpAdapter();
			};


			mGridView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
				var intent = new Intent (this.Activity, typeof(ShowDetailsActivity));
				intent.PutExtra ("TVDBID", "" + showsJToken [e.Position] ["id"]);
				StartActivity (intent);


//				Toast.MakeText (this.Activity, "I clicked on position " + e.Position + " with TVDBID of "
//				+ showsJToken [e.Position] ["id"], ToastLength.Short).Show ();
			};

			return root;
		}
Пример #14
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            OnCreate(savedInstanceState, Resource.Layout.RouteActivity);
            Title = "Itinéraire";

            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            // Handle bundle parameter
            Bundle extras = Intent.Extras;

            if (extras != null && extras.ContainsKey("RouteSegments"))
            {
                string[] routeSegmentsData = extras.GetStringArray("RouteSegments");

                routeSegments = new List <RouteSegment>();
                foreach (string routeSegmentData in routeSegmentsData)
                {
                    JObject routeSegmentObject = JsonConvert.DeserializeObject(routeSegmentData) as JObject;
                    if (routeSegmentObject == null)
                    {
                        throw new Exception("Unable to decode specified route information");
                    }

                    Line line = TramUrWayApplication.GetLine(routeSegmentObject["Line"].Value <int>());

                    int      fromRouteId = routeSegmentObject["From.Route"].Value <int>();
                    int      fromStopId  = routeSegmentObject["From.Stop"].Value <int>();
                    DateTime fromDate    = routeSegmentObject["From.Date"].Value <DateTime>();

                    int      toRouteId = routeSegmentObject["To.Route"].Value <int>();
                    int      toStopId  = routeSegmentObject["To.Stop"].Value <int>();
                    DateTime toDate    = routeSegmentObject["To.Date"].Value <DateTime>();

                    Route fromRoute = line.Routes.First(r => r.Id == fromRouteId);
                    Step  from      = fromRoute.Steps.First(s => s.Stop.Id == fromStopId);

                    Route toRoute = line.Routes.First(r => r.Id == toRouteId);
                    Step  to      = toRoute.Steps.First(s => s.Stop.Id == toStopId);

                    List <TimeStep> timeSteps = new List <TimeStep>();

                    foreach (JObject timeStepObject in routeSegmentObject["TimeSteps"] as JArray)
                    {
                        int      routeId = timeStepObject["Route"].Value <int>();
                        int      stopId  = timeStepObject["Stop"].Value <int>();
                        DateTime date    = timeStepObject["Date"].Value <DateTime>();

                        Route route = line.Routes.First(r => r.Id == routeId);
                        Step  step  = fromRoute.Steps.First(s => s.Stop.Id == stopId);

                        timeSteps.Add(new TimeStep()
                        {
                            Step = step, Date = date
                        });
                    }

                    routeSegments.Add(new RouteSegment()
                    {
                        Line = line, From = from, DateFrom = fromDate, To = to, DateTo = toDate, TimeSteps = timeSteps.ToArray()
                    });
                }

                from = routeSegments.First().From.Stop;
                to   = routeSegments.Last().To.Stop;
            }

            if (from == null || to == null)
            {
                throw new Exception("Could not find specified route information");
            }

            // Initialize UI
            ImageView fromIconView = FindViewById <ImageView>(Resource.Id.RouteActivity_FromIcon);

            fromIconView.SetImageDrawable(from.Line.GetIconDrawable(this));

            TextView fromNameView = FindViewById <TextView>(Resource.Id.RouteActivity_FromName);

            fromNameView.Text = from.Name;

            TextView fromDateView = FindViewById <TextView>(Resource.Id.RouteActivity_FromDate);

            fromDateView.Text = routeSegments.First().DateFrom.ToString("HH:mm");

            ImageView toIconView = FindViewById <ImageView>(Resource.Id.RouteActivity_ToIcon);

            toIconView.SetImageDrawable(to.Line.GetIconDrawable(this));

            TextView toNameView = FindViewById <TextView>(Resource.Id.RouteActivity_ToName);

            toNameView.Text = to.Name;

            TextView toDateView = FindViewById <TextView>(Resource.Id.RouteActivity_ToDate);

            toDateView.Text = routeSegments.Last().DateTo.ToString("HH:mm");

            // Details view
            RecyclerView recyclerView = FindViewById <RecyclerView>(Resource.Id.RouteActivity_SegmentsList);

            recyclerView.SetLayoutManager(new WrapLayoutManager(recyclerView.Context));
            recyclerView.AddItemDecoration(new DividerItemDecoration(recyclerView.Context, LinearLayoutManager.Vertical, true));
            recyclerView.SetAdapter(new RouteSegmentAdapter(routeSegments.ToArray()));
            recyclerView.NestedScrollingEnabled = false;

            // Setup maps fragment
            mapFragment = SupportFragmentManager.FindFragmentById(Resource.Id.RouteActivity_Map) as SupportMapFragment;
            mapFragment.GetMapAsync(this);
        }
        public override void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            Activity act = Activity;

            /* BEGIN_INCLUDE (GET_CURRENT_RESTRICTIONS) */
            // Existing app restriction settings, if exist, can be retrieved from the Bundle.
            mRestrictionsBundle = act.Intent.GetBundleExtra(Intent.ExtraRestrictionsBundle);

            if (mRestrictionsBundle == null)
            {
                mRestrictionsBundle = ((UserManager)act.GetSystemService(Context.UserService))
                                      .GetApplicationRestrictions(Activity.PackageName);
            }

            if (mRestrictionsBundle == null)
            {
                mRestrictionsBundle = new Bundle();
            }

            mRestrictions = (List <IParcelable>)act.Intent.GetParcelableArrayListExtra(Intent.ExtraRestrictionsList);
            /* END_INCLUDE (GET_CURRENT_RESTRICTIONS) */

            // Transfers the saved values into the preference hierarchy.
            if (mRestrictions != null)
            {
                foreach (RestrictionEntry entry in mRestrictions)
                {
                    if (entry.Key.Equals(GetRestrictionsReceiver.KEY_BOOLEAN))
                    {
                        mBooleanPref.Checked = entry.SelectedState;
                        mBooleanEntry        = entry;
                    }
                    else if (entry.Key.Equals(GetRestrictionsReceiver.KEY_CHOICE))
                    {
                        mChoicePref.Value = entry.SelectedString;
                        mChoiceEntry      = entry;
                    }
                    else if (entry.Key.Equals(GetRestrictionsReceiver.KEY_MULTI_SELECT))
                    {
                        List <String> list = new List <String> ();
                        foreach (String value in entry.GetAllSelectedStrings())
                        {
                            list.Add(value);
                        }
                        mMultiPref.Values = list;
                        mMultiEntry       = entry;
                    }
                }
            }
            else
            {
                mRestrictions = new List <IParcelable> ();

                // Initializes the boolean restriction entry and updates its corresponding shared
                // preference value.
                mBooleanEntry = new RestrictionEntry(GetRestrictionsReceiver.KEY_BOOLEAN,
                                                     mRestrictionsBundle.GetBoolean(GetRestrictionsReceiver.KEY_BOOLEAN, false));
                mBooleanEntry.Type   = RestrictionEntryType.Boolean;
                mBooleanPref.Checked = mBooleanEntry.SelectedState;

                // Initializes the single choice restriction entry and updates its corresponding
                // shared preference value.
                mChoiceEntry = new RestrictionEntry(GetRestrictionsReceiver.KEY_CHOICE,
                                                    mRestrictionsBundle.GetString(GetRestrictionsReceiver.KEY_CHOICE));
                mChoiceEntry.Type = RestrictionEntryType.Choice;
                mChoicePref.Value = mChoiceEntry.SelectedString;

                // Initializes the multi-select restriction entry and updates its corresponding
                // shared preference value.
                mMultiEntry = new RestrictionEntry(GetRestrictionsReceiver.KEY_MULTI_SELECT,
                                                   mRestrictionsBundle.GetStringArray(GetRestrictionsReceiver.KEY_MULTI_SELECT));
                mMultiEntry.Type = RestrictionEntryType.MultiSelect;

                if (mMultiEntry.GetAllSelectedStrings() != null)
                {
                    List <String> hset   = new List <String> ();
                    String[]      values = mRestrictionsBundle.GetStringArray(GetRestrictionsReceiver.KEY_MULTI_SELECT);

                    if (values != null)
                    {
                        foreach (String value in values)
                        {
                            hset.Add(value);
                        }
                    }
                    mMultiPref.Values = hset;
                }
                mRestrictions.Add(mBooleanEntry);
                mRestrictions.Add(mChoiceEntry);
                mRestrictions.Add(mMultiEntry);
            }
            // Prepares result to be passed back to the Settings app when the custom restrictions
            // activity finishes.
            Intent intent = new Intent(Activity.Intent);

            intent.PutParcelableArrayListExtra(Intent.ExtraRestrictionsList, new List <IParcelable> (mRestrictions));
            Activity.SetResult(Result.Ok, intent);
        }
Пример #16
0
        /// <summary>
        /// Pushes a local notification instantly.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="bundle"></param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task LocalNotificationNow(Context context, Bundle bundle)
        {
            try
            {
                string requiredParams = CheckRequiredParams(context, bundle, CoreConstants.NotificationType.Now);
                if (requiredParams != Success)
                {
                    throw new System.Exception(requiredParams);
                }

                string channelId  = bundle.GetString(NotificationConstants.ChannelId, CoreConstants.NotificationChannelId);
                int    priority   = bundle.GetPriority();
                int    importance = bundle.GetImportance();
                int    visibility = bundle.GetVisibility();

                channelId += '-' + importance;


                int    smallIcon          = bundle.GetInt(NotificationConstants.SmallIcon);
                bool   isOngoing          = bundle.GetBoolean(NotificationConstants.Ongoing, false);
                bool   isOnlyAlertOnce    = bundle.GetBoolean(NotificationConstants.OnlyAlertOnce, false);
                bool   isAutoCancel       = bundle.GetBoolean(NotificationConstants.AutoCancel, true);
                bool   isGroupSummary     = bundle.GetBoolean(NotificationConstants.GroupSummary, false);
                bool   showWhen           = bundle.GetBoolean(NotificationConstants.ShowWhen, true);
                string ticker             = bundle.GetString(NotificationConstants.Ticker, "Optional Ticker");
                string channelDescription = bundle.GetString(NotificationConstants.ChannelDescription, string.Empty);
                string channelName        = bundle.GetString(NotificationConstants.ChannelName, CoreConstants.ChannelName);
                string message            = bundle.GetString(NotificationConstants.Message, string.Empty);
                string title   = bundle.GetString(NotificationConstants.Title, string.Empty);
                string bigText = bundle.GetString(NotificationConstants.BigText, string.Empty);
                bigText ??= message;

                // Instantiate the builder and set notification elements:
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "")
                                                     .SetVisibility(visibility)
                                                     .SetContentTitle(title)
                                                     .SetContentText(message)
                                                     .SetSmallIcon(smallIcon)
                                                     .SetPriority(priority)
                                                     .SetTicker(ticker)
                                                     .SetAutoCancel(isAutoCancel)
                                                     .SetOnlyAlertOnce(isOnlyAlertOnce)
                                                     .SetOngoing(isOngoing);

                if (bundle.ContainsKey(NotificationConstants.Number))
                {
                    builder.SetBadgeIconType(NotificationCompat.BadgeIconSmall);
                    builder.SetNumber(bundle.GetInt(NotificationConstants.Number));
                }

                //Big Picture Url
                if (bundle.ContainsKey(NotificationConstants.BigPictureUrl))
                {
                    Bitmap bitmap = await Utils.Utils.GetBitmapFromUrlAsync(bundle.GetString(NotificationConstants.BigPictureUrl));

                    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
                    style.BigPicture(bitmap);
                    builder.SetStyle(style);
                }
                else
                {
                    NotificationCompat.Style style = new NotificationCompat.BigTextStyle().BigText(bigText);
                    builder.SetStyle(style);
                }

                //Large Icon Url
                if (bundle.GetString(NotificationConstants.LargeIconUrl) != null)
                {
                    Bitmap largeIconBitmap = await Utils.Utils.GetBitmapFromUrlAsync(bundle.GetString(NotificationConstants.LargeIconUrl));

                    builder.SetLargeIcon(largeIconBitmap);
                }
                else if (bundle.GetInt(NotificationConstants.LargeIcon, -1) != -1)
                {
                    builder.SetLargeIcon(BitmapFactory.DecodeResource(context.Resources, bundle.GetInt(NotificationConstants.LargeIcon)));
                }

                //Vibrate
                long[] vibratePattern = new long[] { 0 };
                if (bundle.GetBoolean(NotificationConstants.Vibrate, false))
                {
                    long vibrateDuration = bundle.ContainsKey(NotificationConstants.VibrateDuration) ?
                                           bundle.GetLong(NotificationConstants.VibrateDuration) : CoreConstants.DefaultVibrateDuration;
                    vibratePattern = new long[] { 0, vibrateDuration };
                    builder.SetVibrate(vibratePattern);

                    channelId += '-' + vibrateDuration;
                }

                //SubText
                string subText = bundle.GetString(NotificationConstants.SubText);
                if (subText != string.Empty)
                {
                    builder.SetSubText(subText);
                }

                //Sound
                Uri soundUri = null;
                if (bundle.GetBoolean(NotificationConstants.PlaySound, false))
                {
                    soundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

                    string soundName = bundle.GetString(NotificationConstants.SoundName);
                    if (soundName != null)
                    {
                        int resId;
                        if (context.Resources.GetIdentifier(soundName, null, null) == 0)
                        {
                            soundName = soundName.Substring(0, soundName.LastIndexOf('.'));
                        }
                        resId    = context.Resources.GetIdentifier(context.PackageName + ":drawable/" + soundName, null, null);
                        soundUri = Uri.Parse($"{ ContentResolver.SchemeAndroidResource}://{context.PackageName}/{resId}");
                    }

                    channelId += '-' + soundName;
                }

                //ShowWhen
                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    builder.SetShowWhen(showWhen);
                }

                //Defaults
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    builder.SetDefaults(NotificationCompat.FlagShowLights);
                }

                //Group and GroupSummary
                if (Build.VERSION.SdkInt >= BuildVersionCodes.KitkatWatch)
                {
                    string group = bundle.GetString(NotificationConstants.Group);

                    if (group != null)
                    {
                        builder.SetGroup(group);
                    }

                    if (bundle.ContainsKey(NotificationConstants.GroupSummary) || isGroupSummary)
                    {
                        builder.SetGroupSummary(isGroupSummary);
                    }
                }

                //Category Color
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    builder.SetCategory(NotificationCompat.CategoryCall);

                    string color = bundle.GetString(NotificationConstants.Color);
                    if (color != null)
                    {
                        builder.SetColor(Color.ParseColor(color));
                    }
                }

                int notificationId = bundle.GetInt(NotificationConstants.Id, CoreUtils.GetRandomInt());
                bundle.PutInt(NotificationConstants.Id, notificationId);

                Class intentClass = Class.ForName(context.PackageManager.GetLaunchIntentForPackage(context.PackageName).Component.ClassName);

                Intent intent = new Intent(context, intentClass);
                intent.AddFlags(ActivityFlags.SingleTop);
                intent.PutExtra(NotificationConstants.Notification, bundle);

                PendingIntent pendingIntent = PendingIntent.GetActivity(context, notificationId, intent,
                                                                        PendingIntentFlags.UpdateCurrent);

                CreateNotificationChannel(context, channelId, channelName, channelDescription, soundUri, (NotificationImportance)importance, vibratePattern);
                builder.SetChannelId(channelId);
                builder.SetContentIntent(pendingIntent);

                string[] actionArr = null;
                try
                {
                    if (bundle.ContainsKey(NotificationConstants.Actions))
                    {
                        actionArr = bundle.GetStringArray(NotificationConstants.Actions);
                    }
                }
                catch { }
                if (actionArr != null)
                {
                    int icon = 0;

                    for (int i = 0; i < actionArr.Length; i++)
                    {
                        string action;
                        try
                        {
                            action = actionArr[i];
                        }
                        catch
                        {
                            continue;
                        }
                        Class  cls          = Class.FromType(typeof(HmsLocalNotificationActionsReceiver));
                        Intent actionIntent = new Intent(context, cls);
                        actionIntent.SetAction(context.PackageName + ".ACTION_" + i);

                        actionIntent.AddFlags(ActivityFlags.SingleTop);

                        bundle.PutString(NotificationConstants.Action, action);
                        actionIntent.PutExtra(NotificationConstants.Notification, bundle);
                        actionIntent.SetPackage(context.PackageName);

                        PendingIntent pendingActionIntent = PendingIntent.GetBroadcast(context, notificationId, actionIntent, PendingIntentFlags.UpdateCurrent);


                        if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                        {
                            builder.AddAction(new NotificationCompat.Action.Builder(icon, action, pendingActionIntent).Build());
                        }
                        else
                        {
                            builder.AddAction(icon, action, pendingActionIntent);
                        }
                    }
                }


                // Build the notification:
                Notification notification = builder.Build();

                ISharedPreferences sharedPreferences = context.GetSharedPreferences(CoreConstants.PreferenceName, FileCreationMode.Private);
                string             id = bundle.GetInt(NotificationConstants.Id).ToString();
                if (sharedPreferences.GetString(id, null) != null)
                {
                    ISharedPreferencesEditor editor = sharedPreferences.Edit();
                    editor.Remove(bundle.GetInt(NotificationConstants.Id).ToString());
                    editor.Apply();
                }

                // Publish the notification:
                if (!(Utils.Utils.IsApplicationInForeground(context) && bundle.GetBoolean(NotificationConstants.DontNotifyInForeground, false)))
                {
                    string tag = bundle.GetString(NotificationConstants.Tag);
                    if (tag != string.Empty && tag != null)
                    {
                        Utils.Utils.GetNotificationManager(context).Notify(tag, notificationId, notification);
                    }
                    else
                    {
                        Utils.Utils.GetNotificationManager(context).Notify(notificationId, notification);
                    }
                }
                LocalNotificationRepeat(context, bundle);

                Log.Info("LocalNotificationNow", Success + bundle.ToJsonObject().ToString());
                return;
            }
            catch (System.Exception e)
            {
                Log.Error("LocalNotificationNow", e.ToString());
                throw e;
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            // changing CultureInfo to en-GB to show decimal point as "." instead of ","
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

            // creating an array of 36 TextViews used for storing every cell from TableLayout
            int textViewCount = 36;

            textViewArray = new TextView[textViewCount];

            // assigning resources to local variables
            Spinner     spinner       = FindViewById <Spinner>(Resource.Id.spinnerPrimaryType);
            Spinner     spinner2      = FindViewById <Spinner>(Resource.Id.spinnerSecondaryType);
            Button      showDmgButton = FindViewById <Button>(Resource.Id.showDmgButton);
            TableLayout tableLayout1  = FindViewById <TableLayout>(Resource.Id.tableLayout1);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            // filling textViewArray with TextViews from TableLayout
            int y = 0;

            for (int i = 1; i < tableLayout1.ChildCount; i++)
            {
                View child = tableLayout1.GetChildAt(i);

                if (child is TableRow row)
                {
                    for (int x = 0; x < row.ChildCount; x++)
                    {
                        View view = row.GetChildAt(x);
                        textViewArray[y] = (TextView)view;
                        ++y;
                    }
                }
            }
            // restoring saved data when screen orientation is changed
            if (savedInstanceState != null)
            {
                string[] temp       = savedInstanceState.GetStringArray("savedArray");
                int[]    tempColors = savedInstanceState.GetIntArray("savedColors");
                selectedSorting = savedInstanceState.GetInt("savedSorting");

                for (int d = 0; d < 36; d++)
                {
                    textViewArray[d].Text = temp[d];
                    Android.Graphics.Color backgroundColor = new Android.Graphics.Color(tempColors[d]);
                    textViewArray[d].SetBackgroundColor(backgroundColor);
                }
                if (temp[0] != "")
                {
                    tableLayout1.SetColumnCollapsed(0, false);
                    tableLayout1.SetColumnCollapsed(1, false);
                }
            }
            // creating 2 custom spinner adapters and assigning them to the primary and secondary pokemon type spinners
            ColorfulSpinnerAdapter adapter  = new ColorfulSpinnerAdapter(this, Resource.Array.pokemonType, Resource.Layout.spinner_item);
            ColorfulSpinnerAdapter adapter2 = new ColorfulSpinnerAdapter(this, Resource.Array.pokemonType, Resource.Layout.spinner_item);

            spinner.Adapter  = adapter;
            spinner2.Adapter = adapter2;

            // creating local variables used for filling TextViews
            string         type1   = string.Empty;
            string         type2   = string.Empty;
            TypeCalculator dmgCalc = new TypeCalculator();

            PkmnType[] typez;
            PkmnType[] typez2;

            showDmgButton.Click += (sender, e) =>
            {
                // checks spinner content
                type1 = spinner.SelectedItem.ToString();
                type2 = spinner2.SelectedItem.ToString();
                // check if one of chosen types is (none)
                if (string.Equals(type1, Resources.GetString(Resource.String.notype)))
                {
                    if (string.Equals(type2, Resources.GetString(Resource.String.notype)))
                    {
                        // fill TextViews of TableLayout with empty strings if both chosen types are (none)
                        for (int d = 0; d < textViewCount; d++)
                        {
                            textViewArray[d].Text = "";
                        }
                        // hide table
                        tableLayout1.SetColumnCollapsed(0, true);
                        tableLayout1.SetColumnCollapsed(1, true);
                    }
                    else
                    {
                        // if the secondary type is not (none) check type and start filling table with sorted values
                        typez = dmgCalc.CheckType(type2);
                        // check selected sorting option
                        if (selectedSorting == menu.GetItem(2).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypes(typez);
                        }
                        else if (selectedSorting == menu.GetItem(1).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypesByName(typez);
                        }
                        for (int d = 0, t = 0; d < textViewCount - 1; d += 2, t++)
                        {
                            textViewArray[d].Text = typez[t].TypeName;
                            textViewArray[d].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].Text = typez[t].DmgTaken.ToString() + "x";
                        }
                        // show table
                        tableLayout1.SetColumnCollapsed(0, false);
                        tableLayout1.SetColumnCollapsed(1, false);
                    }
                }
                else
                {
                    // if secondary type equals (none) or both types are the same check only primary type dmg multipliers
                    if (string.Equals(type2, Resources.GetString(Resource.String.notype)) || string.Equals(type2, type1))
                    {
                        typez = dmgCalc.CheckType(type1);
                        // check selected sorting option
                        if (selectedSorting == menu.GetItem(2).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypes(typez);
                        }
                        else if (selectedSorting == menu.GetItem(1).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypesByName(typez);
                        }
                        for (int d = 0, t = 0; d < textViewCount - 1; d += 2, t++)
                        {
                            textViewArray[d].Text = typez[t].TypeName;
                            textViewArray[d].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].Text = typez[t].DmgTaken.ToString() + "x";
                        }
                    }
                    else
                    {
                        // if both types are different and none of them equals (none) check both types and
                        // multiply primary type multipliers by secondary type multipliers
                        typez  = dmgCalc.CheckType(type1);
                        typez2 = dmgCalc.CheckType(type2);
                        for (int i = 0; i < 18; ++i)
                        {
                            typez[i].DmgTaken *= typez2[i].DmgTaken;
                        }
                        // check selected sorting option
                        if (selectedSorting == menu.GetItem(2).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypes(typez);
                        }
                        else if (selectedSorting == menu.GetItem(1).ItemId)
                        {
                            typez = dmgCalc.SortPkmnTypesByName(typez);
                        }
                        for (int d = 0, t = 0; d < textViewCount - 1; d += 2, t++)
                        {
                            textViewArray[d].Text = typez[t].TypeName;
                            textViewArray[d].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].SetBackgroundColor(typez[t].TypeColor);
                            textViewArray[d + 1].Text = typez[t].DmgTaken.ToString() + "x";
                        }
                    }
                    tableLayout1.SetColumnCollapsed(0, false);
                    tableLayout1.SetColumnCollapsed(1, false);
                }
            };
        }
		private void CreateRestrictions (Context context, PendingResult result, Bundle existingRestrictions) 
		{
			// The incoming restrictions bundle contains key/value pairs representing existing app
			// restrictions for this package. In order to retain existing app restrictions, you need to
			// construct new restriction entries and then copy in any existing values for the new keys.
			List <IParcelable> newEntries = InitRestrictions (context);

			// If app restrictions were not previously configured for the package, create the default
			// restrictions entries and return them.
			if (existingRestrictions == null) {
				var extras = new Bundle ();
				extras.PutParcelableArrayList (Intent.ExtraRestrictionsList, newEntries);
				result.SetResult (Result.Ok, null, extras);
				result.Finish ();
				return;
			}

			// Retains current restriction settings by transferring existing restriction entries to
			// new ones.
			foreach (RestrictionEntry entry in newEntries) {
				String key = entry.Key;

				if (KEY_BOOLEAN.Equals (key)) {
					entry.SelectedState = existingRestrictions.GetBoolean (KEY_BOOLEAN);

				} else if (KEY_CHOICE.Equals (key)) {
					if (existingRestrictions.ContainsKey (KEY_CHOICE)) {
						entry.SelectedString = existingRestrictions.GetString (KEY_CHOICE);
					}
			
				} else if (KEY_MULTI_SELECT.Equals (key)) {
					if (existingRestrictions.ContainsKey (KEY_MULTI_SELECT)) {
						entry.SetAllSelectedStrings(existingRestrictions.GetStringArray (key));
					}
				}
			}

			var extra = new Bundle();

			// This path demonstrates the use of a custom app restriction activity instead of standard
			// types.  When a custom activity is set, the standard types will not be available under
			// app restriction settings.
			//
			// If your app has an existing activity for app restriction configuration, you can set it
			// up with the intent here.
			if (PreferenceManager.GetDefaultSharedPreferences (context)
			    .GetBoolean (MainActivity.CUSTOM_CONFIG_KEY, false)) {
				var customIntent = new Intent();
				customIntent.SetClass (context, typeof (CustomRestrictionsActivity));
				extra.PutParcelable (Intent.ExtraRestrictionsIntent, customIntent);
			}

			extra.PutParcelableArrayList (Intent.ExtraRestrictionsList, newEntries);
			result.SetResult (Result.Ok, null, extra);
			result.Finish ();
		}
        private void CreateRestrictions(Context context, PendingResult result, Bundle existingRestrictions)
        {
            // The incoming restrictions bundle contains key/value pairs representing existing app
            // restrictions for this package. In order to retain existing app restrictions, you need to
            // construct new restriction entries and then copy in any existing values for the new keys.
            List <IParcelable> newEntries = InitRestrictions(context);

            // If app restrictions were not previously configured for the package, create the default
            // restrictions entries and return them.
            if (existingRestrictions == null)
            {
                var extras = new Bundle();
                extras.PutParcelableArrayList(Intent.ExtraRestrictionsList, newEntries);
                result.SetResult(Result.Ok, null, extras);
                result.Finish();
                return;
            }

            // Retains current restriction settings by transferring existing restriction entries to
            // new ones.
            foreach (RestrictionEntry entry in newEntries)
            {
                String key = entry.Key;

                if (KEY_BOOLEAN.Equals(key))
                {
                    entry.SelectedState = existingRestrictions.GetBoolean(KEY_BOOLEAN);
                }
                else if (KEY_CHOICE.Equals(key))
                {
                    if (existingRestrictions.ContainsKey(KEY_CHOICE))
                    {
                        entry.SelectedString = existingRestrictions.GetString(KEY_CHOICE);
                    }
                }
                else if (KEY_MULTI_SELECT.Equals(key))
                {
                    if (existingRestrictions.ContainsKey(KEY_MULTI_SELECT))
                    {
                        entry.SetAllSelectedStrings(existingRestrictions.GetStringArray(key));
                    }
                }
            }

            var extra = new Bundle();

            // This path demonstrates the use of a custom app restriction activity instead of standard
            // types.  When a custom activity is set, the standard types will not be available under
            // app restriction settings.
            //
            // If your app has an existing activity for app restriction configuration, you can set it
            // up with the intent here.
            if (PreferenceManager.GetDefaultSharedPreferences(context)
                .GetBoolean(MainActivity.CUSTOM_CONFIG_KEY, false))
            {
                var customIntent = new Intent();
                customIntent.SetClass(context, typeof(CustomRestrictionsActivity));
                extra.PutParcelable(Intent.ExtraRestrictionsIntent, customIntent);
            }

            extra.PutParcelableArrayList(Intent.ExtraRestrictionsList, newEntries);
            result.SetResult(Result.Ok, null, extra);
            result.Finish();
        }
Пример #20
0
            public override void Run()
            {
                string[] funsname    = bundle.GetStringArray("funsname");
                string[] funsurl     = bundle.GetStringArray("funsurl");
                string[] funsiconurl = bundle.GetStringArray("funsiconurl");
                string[] funsbdnurl  = bundle.GetStringArray("funsbdnurl");
                for (int i = 0; i < funsname.Length; i++)
                {
                    Bitmap bm    = context.getbitmap(funsiconurl[i]);
                    Bitmap bdgbm = context.getbitmap(funsbdnurl[i]);
                    if (bm != null)
                    {
                        MyImageButton fun = new MyImageButton(context, bm, funsname[i], funsurl[i], funsbdnurl[i]);
                        context.myfunslist.Add(fun);
                        fun.Click += (sender, e) =>
                        {
                            Intent intent = new Intent(context, typeof(Detail));
                            intent.PutExtra("Tourl", fun.mToURL);
                            context.StartActivity(intent);
                        };
                        if (Android.OS.Environment.MediaMounted.Equals(Android.OS.Environment.ExternalStorageState))
                        {
                            string imgsavepath = Android.OS.Environment.ExternalStorageDirectory +
                                                 File.Separator + "CommFramework" + File.Separator;
                            File tmpfile    = new File(imgsavepath, "funimg" + i.ToString() + ".png");
                            File tmpicofile = new File(imgsavepath, "funicoimg" + i.ToString() + ".png");
                            tmpfile.ParentFile.Mkdirs();
                            if (tmpfile.Exists())
                            {
                                tmpfile.Delete();
                            }
                            if (tmpicofile.Exists())
                            {
                                tmpicofile.Delete();
                            }
                            try
                            {
                                System.IO.FileStream fos = System.IO.File.Create(imgsavepath + "funimg" + i.ToString() + ".png");

                                bm.Compress(Bitmap.CompressFormat.Png, 90, (System.IO.Stream)fos);
                                fos.Flush();
                                fos.Close();

                                System.IO.FileStream ficos = System.IO.File.Create(imgsavepath + "funicoimg" + i.ToString() + ".png");

                                bdgbm.Compress(Bitmap.CompressFormat.Png, 90, (System.IO.Stream)ficos);
                                ficos.Flush();
                                ficos.Close();
                                context.savelist.Add(funsname[i] + "|" + funsurl[i]);
                            }
                            catch (FileNotFoundException e)
                            {
                                // TODO Auto-generated catch block
                                e.PrintStackTrace();
                            }
                            catch (IOException e)
                            {
                                // TODO Auto-generated catch block
                                e.PrintStackTrace();
                            }
                        }
                        context.mSharedPreference.Edit().PutStringSet("funslist", context.savelist).Commit();
                    }
                }
                if (context.myfunslist.Count > 0)
                {
                    Message msg = context.mainhandler.ObtainMessage();
                    //Bundle bundlefun = new Bundle();
                    msg.What = 2;
                    // bundlefun.PutParcelableArrayList(Constant.MYBUTTON, context.myfunslist);

                    msg.Target = context.mainhandler;
                    msg.SendToTarget();
                }
            }