Esempio n. 1
0
        public RemoteViews GetViewAt(int position)
        {
            var view = new RemoteViews(context.PackageName, Resource.Layout.SuggestionsWidgetItem);

            var item           = items[position];
            var hasDescription = !string.IsNullOrEmpty(item.Description);
            var hasProject     = !string.IsNullOrEmpty(item.ProjectName);

            view.SetViewVisibility(Resource.Id.DescriptionTextView, hasDescription.ToVisibility());
            if (hasDescription)
            {
                view.SetTextViewText(Resource.Id.DescriptionTextView, item.Description);
            }

            view.SetViewVisibility(Resource.Id.ProjectClientRow, hasProject.ToVisibility());

            if (hasProject)
            {
                view.SetTextViewText(Resource.Id.ProjectNameTextView, item.ProjectName);
                view.SetTextColor(Resource.Id.ProjectNameTextView, Color.ParseColor(item.ProjectColor));
                view.SetTextViewText(Resource.Id.ClientNameTextView, item.ClientName);
            }

            var bottomBorderVisibility = (position != Count - 1).ToVisibility();

            view.SetViewVisibility(Resource.Id.BottomSeparator, bottomBorderVisibility);

            var intent = new Intent();

            intent.PutExtra(TappedSuggestionIndex, position);
            view.SetOnClickFillInIntent(Resource.Id.RootLayout, intent);

            return(view);
        }
        public override RemoteViews Setup(Context context, TimeEntryWidgetInfo widgetInfo)
        {
            var view = new RemoteViews(context.PackageName, Resource.Layout.TimeEntryWidgetSmall);

            SetupActionsForStartAndStopButtons(context, view);

            view.SetViewVisibility(Resource.Id.StartButton, (!widgetInfo.IsRunning).ToVisibility());
            view.SetViewVisibility(Resource.Id.StopButton, widgetInfo.IsRunning.ToVisibility());

            return(view);
        }
        public RemoteViews GetViewAt(int position)
        {
            var remoteView = new RemoteViews(context.PackageName, Resource.Layout.widget_list_item);
            var rowData    = itemList [position];

            // set if is running
            if (rowData.IsRunning)
            {
                remoteView.SetImageViewResource(Resource.Id.WidgetContinueImageButton, Resource.Drawable.IcWidgetStop);
                remoteView.SetViewVisibility(Resource.Id.DurationChronometer, Android.Views.ViewStates.Visible);
                remoteView.SetViewVisibility(Resource.Id.DurationTextView, Android.Views.ViewStates.Gone);
            }
            else
            {
                remoteView.SetImageViewResource(Resource.Id.WidgetContinueImageButton, Resource.Drawable.IcWidgetPlay);
                remoteView.SetViewVisibility(Resource.Id.DurationChronometer, Android.Views.ViewStates.Gone);
                remoteView.SetViewVisibility(Resource.Id.DurationTextView, Android.Views.ViewStates.Visible);
            }

            // set color
            remoteView.SetInt(Resource.Id.WidgetColorView, "setColorFilter", Color.ParseColor(rowData.Color));
            remoteView.SetOnClickFillInIntent(Resource.Id.WidgetContinueImageButton, ConstructFillIntent(rowData));

            // set content
            remoteView.SetTextViewText(
                Resource.Id.DescriptionTextView,
                String.IsNullOrWhiteSpace(rowData.Description) ? context.Resources.GetString(Resource.String.RunningWidgetNoDescription) : rowData.Description);
            remoteView.SetTextViewText(
                Resource.Id.ProjectTextView,
                String.IsNullOrWhiteSpace(rowData.ProjectName) ? context.Resources.GetString(Resource.String.RunningWidgetNoProject) : rowData.ProjectName);
            remoteView.SetTextViewText(Resource.Id.DurationTextView, rowData.TimeValue);

            var time = (long)rowData.Duration.TotalMilliseconds;

            // Format chronometer correctly.
            string format = "00:%s";

            if (time >= 3600000 && time < 36000000)
            {
                format = "0%s";
            }
            else if (time >= 36000000)
            {
                format = "%s";
            }
            var baseTime = SystemClock.ElapsedRealtime();

            remoteView.SetChronometer(Resource.Id.DurationChronometer, baseTime - (long)rowData.Duration.TotalMilliseconds, format, true);


            return(remoteView);
        }
Esempio n. 4
0
        private void SetupRunningBtn(Context ctx, RemoteViews views)
        {
            var entry     = new WidgetSyncManager.WidgetEntryData();
            var isRunning = false;

            // Check if an entry is running.
            foreach (var item in UpdateService.LastEntries)
            {
                if (item.IsRunning)
                {
                    entry     = item;
                    isRunning = true;
                }
            }

            var baseTime = SystemClock.ElapsedRealtime();

            if (isRunning)
            {
                views.SetInt(Resource.Id.WidgetActionButton, "setBackgroundColor", ctx.Resources.GetColor(Resource.Color.bright_red));
                views.SetInt(Resource.Id.WidgetActionButton, "setText", Resource.String.TimerStopButtonText);
                views.SetInt(Resource.Id.WidgetColorView, "setColorFilter", Color.ParseColor(entry.Color));
                views.SetViewVisibility(Resource.Id.WidgetRunningEntry, ViewStates.Visible);
                views.SetTextViewText(
                    Resource.Id.WidgetRunningDescriptionTextView,
                    String.IsNullOrWhiteSpace(entry.Description) ? ctx.Resources.GetString(Resource.String.RunningWidgetNoDescription) : entry.Description);

                var time = (long)entry.Duration.TotalMilliseconds;

                // Format chronometer correctly.
                string format = "00:%s";
                if (time >= 3600000 && time < 36000000)
                {
                    format = "0%s";
                }
                else if (time >= 36000000)
                {
                    format = "%s";
                }

                views.SetChronometer(Resource.Id.Chronometer, baseTime - (long)entry.Duration.TotalMilliseconds, format, true);
            }
            else
            {
                views.SetInt(Resource.Id.WidgetActionButton, "setBackgroundColor", ctx.Resources.GetColor(Resource.Color.bright_green));
                views.SetInt(Resource.Id.WidgetActionButton, "setText", Resource.String.TimerStartButtonText);
                views.SetViewVisibility(Resource.Id.WidgetRunningEntry, ViewStates.Invisible);
                views.SetChronometer(Resource.Id.Chronometer, baseTime, "00:%s", false);
                views.SetTextViewText(Resource.Id.Chronometer, "00:00:00");
            }
        }
Esempio n. 5
0
        protected RemoteViews Setup(Context context)
        {
            var view = new RemoteViews(context.PackageName, Resource.Layout.WidgetNotLoggedIn);

            view.SetOnClickPendingIntent(Resource.Id.RootLayout, getOpenAppToLoginPendingIntent(context));

            view.SetTextViewText(Resource.Id.NotLoggedInLabel, LabelText);

            view.SetViewVisibility(Resource.Id.NotLoggedInLabel, isFullView.ToVisibility());
            view.SetViewVisibility(Resource.Id.TogglLogo, isFullView.ToVisibility());
            view.SetViewVisibility(Resource.Id.PadLock, isFullView.ToVisibility());
            view.SetViewVisibility(Resource.Id.PadLockBig, (!isFullView).ToVisibility());

            return(view);
        }
Esempio n. 6
0
        public void UpdateWidgets(Context context, AppWidgetManager appWidgetManager,
                                  int[] appWidgetIds, string updateMessage, string totalVal, string profitVal, Color profCol, bool updating, bool setIntents = false)
        {
            for (int i = 0; i < appWidgetIds.Length; i++)
            {
                int         widgetId    = appWidgetIds[i];
                RemoteViews remoteViews = new RemoteViews(context.PackageName, Resource.Layout.Widget);
                remoteViews.SetViewVisibility(Resource.Id.widgetButton, (updating)?
                                              Android.Views.ViewStates.Gone : Android.Views.ViewStates.Visible);
                remoteViews.SetViewVisibility(Resource.Id.widgetLoading, (updating)?
                                              Android.Views.ViewStates.Visible : Android.Views.ViewStates.Gone);

                if (!string.IsNullOrWhiteSpace(profitVal))
                {
                    remoteViews.SetTextViewText(Resource.Id.widgetProfit, profitVal);
                    remoteViews.SetTextColor(Resource.Id.widgetProfit, profCol);
                }

                if (!string.IsNullOrWhiteSpace(totalVal))
                {
                    remoteViews.SetTextViewText(Resource.Id.widgetTotal, totalVal);
                }

                if (!string.IsNullOrWhiteSpace(updateMessage))
                {
                    remoteViews.SetTextViewText(Resource.Id.widgetTime, updateMessage);
                }

                if (setIntents)
                {
                    Intent intent = new Intent(context, typeof(HodlrWidgetProvider));
                    intent.SetAction(AppWidgetManager.ActionAppwidgetUpdate);
                    intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, appWidgetIds);

                    PendingIntent pendingIntent = PendingIntent.GetBroadcast(
                        context, 0, intent, PendingIntentFlags.UpdateCurrent);

                    remoteViews.SetOnClickPendingIntent(Resource.Id.widgetButton, pendingIntent);


                    Intent        activityIntent = new Intent(context, typeof(MainActivity));
                    PendingIntent pendingAct     = PendingIntent.GetActivity(context, 0, activityIntent, 0);
                    remoteViews.SetOnClickPendingIntent(Resource.Id.widgetImage, pendingAct);
                }

                appWidgetManager.UpdateAppWidget(widgetId, remoteViews);
            }
        }
        protected void ShowRefresh(Context context, int[] appWidgetIds)
        {
            var appWidgetManager = AppWidgetManager.GetInstance(context);
            var componentname    = new ComponentName(context.PackageName, ClassName);

            if (appWidgetIds == null || appWidgetIds.Length == 0)
            {
                appWidgetIds = appWidgetManager.GetAppWidgetIds(componentname);
            }

            var views = new RemoteViews(context.PackageName, WidgetLayoutId);

            views.SetViewVisibility(Resource.Id.refresh_button, ViewStates.Gone);
            views.SetViewVisibility(Resource.Id.refresh_progress, ViewStates.Visible);
            appWidgetManager.PartiallyUpdateAppWidget(appWidgetIds, views);
        }
Esempio n. 8
0
        public static void Update(Context context, AppWidgetManager appWidgetManager, params int[] appWidgetIds)
        {
            foreach (int appWidgetId in appWidgetIds)
            {
                Step step;
                if (!TramUrWayApplication.Config.StepWidgets.TryGetValue(appWidgetId, out step))
                {
                    return;
                }

                RemoteViews remoteViews = new RemoteViews(context.PackageName, Resource.Layout.StepWidget);

                Intent intent = new Intent(context, typeof(StopActivity));
                intent.PutExtra("Stop", step.Stop.Id);
                intent.PutExtra("Route", step.Route.Id);

                int code = Util.Hash(step.Stop.Id, step.Route.Id);

                PendingIntent pendingIntent = PendingIntent.GetActivity(context, code, intent, 0);
                remoteViews.SetOnClickPendingIntent(Resource.Id.StepWidget_Button, pendingIntent);

                // Update widget UI
                remoteViews.SetTextViewText(Resource.Id.StepWidget_Name, step.Stop.Name);
                remoteViews.SetViewVisibility(Resource.Id.StepWidget_Description, TramUrWayApplication.Config.EnableWidgetRefresh ? ViewStates.Visible : ViewStates.Gone);

                Bitmap bitmap = Utils.GetTransportIconForLine(context, step.Route.Line, 48);
                remoteViews.SetImageViewBitmap(Resource.Id.StepWidget_Icon, bitmap);

                // Get step information
                if (TramUrWayApplication.Config.EnableWidgetRefresh)
                {
                    DateTime   now       = DateTime.Now;
                    TimeStep[] timeSteps = null;

                    try
                    {
                        timeSteps = TramUrWayApplication.Service.GetLiveTimeSteps(step.Route.Line).Where(t => t.Step.Stop == step.Stop).OrderBy(t => t.Date).Take(2).ToArray();
                    }
                    catch (Exception e)
                    {
                        timeSteps = TramUrWayApplication.Lines.SelectMany(l => l.Routes)
                                    .SelectMany(r => r.Steps.Where(s => s.Stop.Name == step.Stop.Name))
                                    .SelectMany(s => s.Route.TimeTable?.GetStepsFromStep(s, now)?.Take(3) ?? Enumerable.Empty <TimeStep>())
                                    .Take(2)
                                    .ToArray();
                    }

                    remoteViews.SetTextViewText(Resource.Id.StepWidget_Description, timeSteps == null ? "???" : Utils.GetReadableTimes(timeSteps, now, false));
                }

                try
                {
                    appWidgetManager.UpdateAppWidget(appWidgetId, remoteViews);
                }
                catch (Exception e)
                {
                    Toast.MakeText(context, "Exception while updating widget: " + e, ToastLength.Long).Show();
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Renders the visual contents of a specific widget contents into a RemoteViews object
        /// </summary>
        /// <param name="widgetContext">Widget context.</param>
        /// <param name="widgetId">Widget identifier.</param>
        private RemoteViews RenderWidgetContents(Context context, int widgetId)
        {
            // Initialise the persistent storage
            PersistentStorage.StorageMechanism = new StorageMechanism(context);
            PersistentStorage.UseCache         = false;

            // Create a RemoteView for the widget
            RemoteViews widgetView = new RemoteViews(context.PackageName, Resource.Layout.widget);

            // Extract the current trip details and display them.
            // The trip details and selected trip can be changed independently by the main app so a new set of train trip details need to be read
            TrainTrips.Reset();
            TrainTrip selectedTrip = TrainTrips.SelectedTrip;

            if (selectedTrip != null)
            {
                widgetView.SetTextViewText(Resource.Id.widgetTrip, string.Format("{0}:{1}", selectedTrip.FromCode, selectedTrip.ToCode));
            }

            // Extract the next departure time and display it
            DateTime departureTime = NextDeparture.DepartureTime;

            widgetView.SetTextViewText(Resource.Id.widgetDeparture, departureTime.ToString("HH:mm"));

            // Register pending intents for clicking on the displayed fields
            RegisterClicks(context, widgetView);

            // Show the correct image for the running state of the update service
            if (PersistentStorage.GetBoolItem(UpdateInProgressName, false) == true)
            {
                // An update is actually in progress, so show the progress indicator and hide
                // the service status flags
                widgetView.SetViewVisibility(Resource.Id.layoutProgressBar, Android.Views.ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Gone);
            }
            else
            {
                // Hide the progress indicator and show the servide state
                widgetView.SetViewVisibility(Resource.Id.layoutProgressBar, Android.Views.ViewStates.Gone);

                if (PersistentStorage.GetBoolItem(UpdateServiceRunningName, false) == true)
                {
                    widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Gone);
                    widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Visible);
                }
                else
                {
                    widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Visible);
                    widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Gone);
                }
            }

            return(widgetView);
        }
Esempio n. 10
0
        public RemoteViews GetViewAt (int position)
        {
            var remoteView = new RemoteViews (context.PackageName, Resource.Layout.widget_list_item);
            var rowData = itemList [position];

            // set if is running
            if (rowData.IsRunning) {
                remoteView.SetImageViewResource (Resource.Id.WidgetContinueImageButton, Resource.Drawable.IcWidgetStop);
                remoteView.SetViewVisibility (Resource.Id.DurationChronometer, Android.Views.ViewStates.Visible);
                remoteView.SetViewVisibility (Resource.Id.DurationTextView, Android.Views.ViewStates.Gone);
            } else {
                remoteView.SetImageViewResource (Resource.Id.WidgetContinueImageButton, Resource.Drawable.IcWidgetPlay);
                remoteView.SetViewVisibility (Resource.Id.DurationChronometer, Android.Views.ViewStates.Gone);
                remoteView.SetViewVisibility (Resource.Id.DurationTextView, Android.Views.ViewStates.Visible);
            }

            // set color
            remoteView.SetInt (Resource.Id.WidgetColorView, "setColorFilter", Color.ParseColor (rowData.Color));
            remoteView.SetOnClickFillInIntent (Resource.Id.WidgetContinueImageButton, ConstructFillIntent (rowData));

            // set content
            remoteView.SetTextViewText (
                Resource.Id.DescriptionTextView,
                String.IsNullOrWhiteSpace (rowData.Description) ? context.Resources.GetString (Resource.String.RunningWidgetNoDescription) : rowData.Description);
            remoteView.SetTextViewText (
                Resource.Id.ProjectTextView,
                String.IsNullOrWhiteSpace (rowData.ProjectName) ? context.Resources.GetString (Resource.String.RunningWidgetNoProject) : rowData.ProjectName);
            remoteView.SetTextViewText (Resource.Id.DurationTextView, rowData.TimeValue);

            var time = (long)rowData.Duration.TotalMilliseconds;

            // Format chronometer correctly.
            string format = "00:%s";
            if (time >= 3600000 && time < 36000000) {
                format = "0%s";
            } else if (time >= 36000000) {
                format = "%s";
            }
            var baseTime = SystemClock.ElapsedRealtime ();
            remoteView.SetChronometer (Resource.Id.DurationChronometer, baseTime - (long)rowData.Duration.TotalMilliseconds, format, true);


            return remoteView;
        }
Esempio n. 11
0
        /// <summary>
        /// Update the notification.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The updated notification.
        /// </returns>
        public Notification UpdateNotification(Context context)
        {
            bool hasPausedText = this.PausedText != null;
            bool mustUpdate    = this.lastHasPausedText != hasPausedText;

            // Build the RemoteView object
            if (expandedView == null)
            {
                expandedView = new RemoteViews(context.PackageName, Resource.Layout.status_bar_ongoing_event_progress_bar);
                expandedView.SetImageViewResource(Resource.Id.appIcon, this.Icon);
                expandedView.SetTextViewText(Resource.Id.paused_text, this.PausedText);
                expandedView.SetTextViewText(Resource.Id.title, this.Title);

                this.notification.ContentView = expandedView;

                mustUpdate = true;
            }

            if (mustUpdate)
            {
                expandedView.SetViewVisibility(Resource.Id.progress_bar_frame, hasPausedText ? ViewStates.Gone : ViewStates.Visible);
                expandedView.SetViewVisibility(Resource.Id.description, hasPausedText ? ViewStates.Gone : ViewStates.Visible);
                expandedView.SetViewVisibility(Resource.Id.time_remaining, hasPausedText ? ViewStates.Gone : ViewStates.Visible);
                expandedView.SetViewVisibility(Resource.Id.paused_text, hasPausedText ? ViewStates.Visible : ViewStates.Gone);
            }

            if (!hasPausedText)
            {
                expandedView.SetTextViewText(Resource.Id.progress_text, Helpers.GetDownloadProgressPercent(this.CurrentBytes, this.TotalBytes));
                expandedView.SetTextViewText(Resource.Id.description, Helpers.GetDownloadProgressString(this.CurrentBytes, this.TotalBytes));
                expandedView.SetProgressBar(
                    Resource.Id.progress_bar,
                    (int)(this.TotalBytes >> 8),
                    (int)(this.CurrentBytes >> 8),
                    this.TotalBytes <= 0);
                expandedView.SetTextViewText(Resource.Id.time_remaining, string.Format("Time remaining: {0}", Helpers.GetTimeRemaining(this.TimeRemaining)));
            }

            this.lastHasPausedText = hasPausedText;

            return(this.notification);
        }
Esempio n. 12
0
            public RemoteViews GetViewAt(int position)
            {
                var views = new RemoteViews(_applicationContext.PackageName, Resource.Layout.CalendarWidgetItem);
                var vm    = _items[position];

                var intent = new Intent(_applicationContext, typeof(MainActivity));

                intent.PutExtra("launchArgs", $"https://myanimelist.net/anime/{vm.Id}");
                views.SetOnClickFillInIntent(Resource.Id.Image, intent);
                if (ResourceLocator.AiringInfoProvider.TryGetCurrentEpisode(vm.Id, out int ep, DateTime.Today))
                {
                    views.SetTextViewText(Resource.Id.EpisodeCount, $"ep. {ep}");
                    views.SetViewVisibility(Resource.Id.EpisodeCount, ViewStates.Visible);
                }
        protected virtual void UpdateWeatherPart(Context context, RemoteViews view, AppWidgetSettings settings, bool isDemoMode)
        {
            var weather = settings.Weather;
            var utcNow  = DateTime.UtcNow;

            if (isDemoMode && weather == null)
            {
                var weatherDataPoint = new WeatherDataPoint
                {
                    Date           = utcNow,
                    Temperature    = 0,
                    MinTemperature = -1,
                    MaxTemperature = 1,
                    WeatherCode    = WeatherCodes.ClearSky,
                    Condition      = context.GetString(Resource.String.DemoCondition)
                };

                weather = new WeatherForecast(providerId: settings.WeatherProviderId, latitude: null, longitude: null,
                                              units: AppSettings.Default.Units, languageCode: AppSettings.Default.Language, link: null,
                                              hasIcons: false)
                {
                    Currently = weatherDataPoint,
                    Daily     = new[] { weatherDataPoint }
                };
            }

            if (weather?.MaxPublishedDate == null)
            {
                return;
            }

            var actualUtcDate = utcNow > weather.MaxPublishedDate ? weather.MaxPublishedDate.Value : utcNow;
            var currently     = weather.FindActualCurrentlyAsync(actualUtcDate).Result;

            if (currently == null)
            {
                return;
            }

            var temperature = string.Empty;

            using (var weatherTools = new WeatherTools
            {
                ProviderUnits = weather.Units,
            })
            {
                var degree = weatherTools.DegreeString;
                if (currently.Temperature.HasValue)
                {
                    temperature = weatherTools.ConvertTemperatureToString(currently.Temperature.Value, "{0:f0}{1}",
                                                                          degree);
                }
                SetTextFormatted(view, Resource.Id.txtTemp, temperature,
                                 weatherTools.IsTemperatureAlerted(currently.Temperature));

                var minTempText = string.Empty;
                var maxTempText = string.Empty;
                var visibility  = ViewStates.Gone;
                var minTemp     = weatherTools
                                  .CalculateMinTemperatureAsync(actualUtcDate, weather, currently.MinTemperature).Result;
                var maxTemp = weatherTools
                              .CalculateMaxTemperatureAsync(actualUtcDate, weather, currently.MaxTemperature).Result;
                if (minTemp.HasValue && maxTemp.HasValue)
                {
                    minTempText = weatherTools.ConvertTemperatureToString(minTemp.Value, "{0:f0}{1}", degree);
                    maxTempText = weatherTools.ConvertTemperatureToString(maxTemp.Value, "{0:f0}{1}", degree);
                    visibility  = ViewStates.Visible;
                }
                SetTextFormatted(view, Resource.Id.txtLow, minTempText, weatherTools.IsTemperatureAlerted(minTemp));
                view.SetViewVisibility(Resource.Id.txtLowIndicator, visibility);
                SetTextFormatted(view, Resource.Id.txtHigh, maxTempText, weatherTools.IsTemperatureAlerted(maxTemp));
                view.SetViewVisibility(Resource.Id.txtHighIndicator, visibility);

                var conditionIconId = weatherTools.GetConditionIconId(WidgetTypes.AppWidget, settings.WidgetIconStyle,
                                                                      currently, true, true);
                view.SetImageViewResource(Resource.Id.imgCondition, conditionIconId);

                //"Небольшой снегопад "
                SetTextFormatted(view, Resource.Id.txtCondition,
                                 (currently.Condition ?? string.Empty).Trim().ToCapital(),
                                 weatherTools.IsConditionExtreme(currently.WeatherCode));
            }

            var locality = (settings.LocationAddress?.GetDisplayLocality() ?? string.Empty).Trim();

            if (string.IsNullOrEmpty(locality) && isDemoMode)
            {
                locality = context.GetString(settings.UseTrackCurrentLocation
                    ? Resource.String.CurrentLocationEmpty
                    : Resource.String.DemoLocality);
            }
            view.SetTextViewText(Resource.Id.txtLocation, locality);
        }
Esempio n. 14
0
        private void ShowError(RemoteViews widgetView, ErrorType error)
        {
            switch (error)
            {
            case ErrorType.None:
                widgetView.SetViewVisibility(Resource.Id.MainLayout, ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.PlaceName, ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.Description, ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.ErrorConnection, ViewStates.Gone);
                break;

            case ErrorType.LocalizationError:
                widgetView.SetViewVisibility(Resource.Id.MainLayout, ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.PlaceName, ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.Description, ViewStates.Gone);
                widgetView.SetTextViewText(Resource.Id.ErrorConnection, Resources.Translations.GetMissingLocalizationPermissionsText());
                widgetView.SetViewVisibility(Resource.Id.ErrorConnection, ViewStates.Visible);
                break;

            case ErrorType.InternetConnectionError:
                widgetView.SetViewVisibility(Resource.Id.MainLayout, ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.PlaceName, ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.Description, ViewStates.Gone);
                widgetView.SetTextViewText(Resource.Id.ErrorConnection, Resources.Translations.GetNoInternetConnectionText());
                widgetView.SetViewVisibility(Resource.Id.ErrorConnection, ViewStates.Visible);
                break;
            }
        }
        public static void UpdateNotification(Weather weather)
        {
            // Gets an instance of the NotificationManager service
            NotificationManager mNotifyMgr = (NotificationManager)App.Context.GetSystemService(App.NotificationService);

            InitChannel(mNotifyMgr);

            var wm = WeatherManager.GetInstance();

            // Build update
            RemoteViews updateViews = new RemoteViews(App.Context.PackageName, Resource.Layout.notification_layout);

            string temp = (Settings.IsFahrenheit ?
                           Math.Round(weather.condition.temp_f) : Math.Round(weather.condition.temp_c)) + "º";
            string condition = weather.condition.weather;
            string hitemp    = (Settings.IsFahrenheit ?
                                Math.Round(double.Parse(weather.forecast[0].high_f)) : Math.Round(double.Parse(weather.forecast[0].high_c))) + "º";
            string lotemp = (Settings.IsFahrenheit ?
                             Math.Round(double.Parse(weather.forecast[0].low_f)) : Math.Round(double.Parse(weather.forecast[0].low_c))) + "º";

            // Weather icon
            updateViews.SetImageViewResource(Resource.Id.weather_icon,
                                             wm.GetWeatherIconResource(weather.condition.icon));

            // Location Name
            updateViews.SetTextViewText(Resource.Id.location_name, weather.location.name);

            // Condition text
            updateViews.SetTextViewText(Resource.Id.condition_weather, string.Format("{0} - {1}", temp, condition));

            // Details
            updateViews.SetTextViewText(Resource.Id.condition_details,
                                        string.Format("{0} / {1}", hitemp, lotemp));

            // Update Time
            string timeformat = DateTime.Now.ToString("h:mm tt");

            if (DateFormat.Is24HourFormat(App.Context))
            {
                timeformat = DateTime.Now.ToString("HH:mm");
            }

            updateViews.SetTextViewText(Resource.Id.update_time, timeformat);

            // Progress bar
            updateViews.SetViewVisibility(Resource.Id.refresh_button, ViewStates.Visible);
            updateViews.SetViewVisibility(Resource.Id.refresh_progress, ViewStates.Gone);
            Intent refreshClickIntent = new Intent(App.Context, typeof(Widgets.WeatherWidgetBroadcastReceiver))
                                        .SetAction(Widgets.WeatherWidgetService.ACTION_REFRESHNOTIFICATION);
            PendingIntent prgPendingIntent = PendingIntent.GetBroadcast(App.Context, 0, refreshClickIntent, 0);

            updateViews.SetOnClickPendingIntent(Resource.Id.refresh_button, prgPendingIntent);

            if (!int.TryParse(temp.Replace("º", ""), out int level))
            {
                level = 0;
            }

            int resId = level < 0 ? Resource.Drawable.notification_temp_neg : Resource.Drawable.notification_temp_pos;

            NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID)
                .SetContent(updateViews)
                .SetPriority(NotificationCompat.PriorityLow)
                .SetOngoing(true) as NotificationCompat.Builder;

            if (Settings.NotificationIcon == Settings.TEMPERATURE_ICON)
            {
                mBuilder.SetSmallIcon(resId, Math.Abs(level));
            }
            else if (Settings.NotificationIcon == Settings.CONDITION_ICON)
            {
                mBuilder.SetSmallIcon(wm.GetWeatherIconResource(weather.condition.icon));
            }

            Intent onClickIntent = new Intent(App.Context, typeof(MainActivity))
                                   .SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask | ActivityFlags.ClearTask);
            PendingIntent clickPendingIntent = PendingIntent.GetActivity(App.Context, 0, onClickIntent, 0);

            mBuilder.SetContentIntent(clickPendingIntent);

            // Builds the notification and issues it.
            mNotification = mBuilder.Build();
            mNotifyMgr.Notify(PERSISTENT_NOT_ID, mNotification);
            IsShowing = true;
        }
Esempio n. 16
0
        private Notification BuildNotification()
        {
            _notificationBuilder = new NotificationCompat.Builder(ApplicationContext);
            _notificationBuilder.SetOngoing(true);
            _notificationBuilder.SetAutoCancel(false);
            _notificationBuilder.SetSmallIcon(Resource.Drawable.NotifIcon);
            //Open up the player screen when the user taps on the notification.
            var launchNowPlayingIntent = new Intent();

            launchNowPlayingIntent.SetAction(LaunchNowPlayingAction);
            var launchNowPlayingPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, launchNowPlayingIntent,
                                                                           0);

            _notificationBuilder.SetContentIntent(launchNowPlayingPendingIntent);

            //Grab the notification layouts.
            var notificationView = new RemoteViews(ApplicationContext.PackageName,
                                                   Resource.Layout.notification_custom_layout);
            var expNotificationView = new RemoteViews(ApplicationContext.PackageName,
                                                      Resource.Layout.notification_custom_expanded_layout);

            //Initialize the notification layout buttons.
            var previousTrackIntent = new Intent();

            previousTrackIntent.SetAction(PrevAction);
            var previousTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0,
                                                                        previousTrackIntent, 0);

            var playPauseTrackIntent = new Intent();

            playPauseTrackIntent.SetAction(PlayPauseAction);
            var playPauseTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0,
                                                                         playPauseTrackIntent, 0);

            var nextTrackIntent = new Intent();

            nextTrackIntent.SetAction(NextAction);
            var nextTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, nextTrackIntent, 0);

            var stopServiceIntent = new Intent();

            stopServiceIntent.SetAction(StopAction);
            var stopServicePendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, stopServiceIntent,
                                                                      0);

            //Check if audio is playing and set the appropriate play/pause button.
            if (App.Current.AudioServiceConnection.GetPlaybackService().IsPlayingMusic)
            {
                notificationView.SetImageViewResource(Resource.Id.notification_base_play,
                                                      Resource.Drawable.btn_playback_pause_light);
                expNotificationView.SetImageViewResource(Resource.Id.notification_expanded_base_play,
                                                         Resource.Drawable.btn_playback_pause_light);
            }
            else
            {
                notificationView.SetImageViewResource(Resource.Id.notification_base_play,
                                                      Resource.Drawable.btn_playback_play_light);
                expNotificationView.SetImageViewResource(Resource.Id.notification_expanded_base_play,
                                                         Resource.Drawable.btn_playback_play_light);
            }

            var song = AudioPlayerHelper.CurrentQueueSong.Song;

            //Set the notification content.
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_one, song.Name);
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_two, song.ArtistName);
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_three, song.Album.Name);

            notificationView.SetTextViewText(Resource.Id.notification_base_line_one, song.Name);
            notificationView.SetTextViewText(Resource.Id.notification_base_line_two, song.ArtistName);

            //the previous and next buttons, always enabled.
            expNotificationView.SetViewVisibility(Resource.Id.notification_expanded_base_previous, ViewStates.Visible);
            expNotificationView.SetViewVisibility(Resource.Id.notification_expanded_base_next, ViewStates.Visible);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_play,
                                                        playPauseTrackPendingIntent);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_next,
                                                        nextTrackPendingIntent);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_previous,
                                                        previousTrackPendingIntent);

            notificationView.SetViewVisibility(Resource.Id.notification_base_previous, ViewStates.Visible);
            notificationView.SetViewVisibility(Resource.Id.notification_base_next, ViewStates.Visible);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_play, playPauseTrackPendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_next, nextTrackPendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_previous, previousTrackPendingIntent);

            //Set the "Stop Service" pending intents.
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_collapse,
                                                        stopServicePendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_collapse, stopServicePendingIntent);

            //Set the album art.
            if (song.Album.Artwork != null)
            {
                if (song.Album.Artwork.Image != null)
                {
                    expNotificationView.SetImageViewBitmap(Resource.Id.notification_expanded_base_image,
                                                           song.Album.Artwork.Image as Bitmap);
                    notificationView.SetImageViewBitmap(Resource.Id.notification_base_image,
                                                        song.Album.Artwork.Image as Bitmap);
                }
                else
                {
                    ((PclBitmapImage)song.Album.Artwork).PropertyChanged += OnPropertyChanged;
                }
            }
            else
            {
                song.Album.PropertyChanged += OnPropertyChanged;
            }

            //Attach the shrunken layout to the notification.
            _notificationBuilder.SetContent(notificationView);

            //Build the notification object.
            var notification = _notificationBuilder.Build();

            //Attach the expanded layout to the notification and set its flags.
            notification.BigContentView = expNotificationView;
            notification.Flags          = NotificationFlags.ForegroundService |
                                          NotificationFlags.NoClear |
                                          NotificationFlags.OngoingEvent;
            return(notification);
        }
        protected override async void OnHandleIntent(Intent intent)
        {
            var manager = AppWidgetManager.GetInstance(this);

            int[] allWidgetIds = intent
                                 .GetIntArrayExtra(AppWidgetManager.ExtraAppwidgetIds);
            var layoutId = intent.GetIntExtra("ResourceId", Resource.Layout.CalendarWidgetLight);

            _views = new List <Tuple <RemoteViews, int> >();

            try
            {
                ResourceLocator.RegisterBase();
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));

                Credentials.Init();
            }
            catch (Exception e)
            {
            }
            bool running = ResourceLocator.AnimeLibraryDataStorage.AllLoadedAuthAnimeItems?.Any() ?? false;

            foreach (var widgetId in allWidgetIds)
            {
                var view = new RemoteViews(PackageName, layoutId);
                _views.Add(new Tuple <RemoteViews, int>(view, widgetId));

                view.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Visible);
                view.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Gone);
                //view.SetViewVisibility(Resource.Id.RefreshButton, ViewStates.Gone);
                view.SetViewVisibility(Resource.Id.GridView, ViewStates.Gone);

                manager.UpdateAppWidget(widgetId, view);
            }

            CalendarPivotPage shows = null;

            try
            {
                if (Credentials.Authenticated)
                {
                    if (!running)
                    {
                        await ResourceLocator.AiringInfoProvider.Init(false);

                        ViewModelLocator.AnimeList.ListSource = Credentials.UserName;
                        await ViewModelLocator.AnimeList.FetchData(true, AnimeListWorkModes.Anime);
                    }
                    if (ResourceLocator.AiringInfoProvider.InitializationSuccess && (ResourceLocator.AnimeLibraryDataStorage.AllLoadedAuthAnimeItems?.Any() ?? false))
                    {
                        await ViewModelLocator.CalendarPage.Init(true);

                        shows =
                            ViewModelLocator.CalendarPage.CalendarData.FirstOrDefault(
                                page => page.DayOfWeek == DateTime.Now.DayOfWeek);
                    }
                }
            }
            catch (Exception e)
            {
                //we have failed very very badly
            }

            await Task.Delay(1000); // give visual feedback


            if (shows != null && shows.Items.Any())
            {
                foreach (var view in _views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Visible);
                    view.Item1.SetRemoteAdapter(Resource.Id.GridView, new Intent(ApplicationContext, typeof(CalendarWidgetRemoteViewsService)));

                    var intentTemplate = new Intent(ApplicationContext, typeof(MainActivity));
                    view.Item1.SetPendingIntentTemplate(Resource.Id.GridView, PendingIntent.GetActivity(ApplicationContext, 0, intentTemplate, 0));

                    var refreshIntent = new Intent(ApplicationContext, typeof(CalendarWidgetUpdateService));
                    refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, new[] { view.Item2 });
                    refreshIntent.PutExtra("ResourceId", layoutId);
                    view.Item1.SetOnClickPendingIntent(Resource.Id.RefreshButton, PendingIntent.GetService(ApplicationContext, 0, refreshIntent, 0));

                    var preferences = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                    var ids         = preferences.GetStringSet("lastWidgetItems", new List <string>()).Select(int.Parse).ToList();
                    if (!ids.OrderBy(i => i).SequenceEqual(shows.Items.Select(model => model.Id).OrderBy(i => i)))
                    {
                        manager.NotifyAppWidgetViewDataChanged(view.Item2, Resource.Id.GridView);

                        var edit = preferences.Edit();
                        edit.PutStringSet("lastWidgetItems", shows.Items.Select(model => model.Id.ToString()).ToList());
                        edit.Commit();
                    }



                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }
            else
            {
                foreach (var view in _views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Visible);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Gone);


                    var refreshIntent = new Intent(ApplicationContext, typeof(CalendarWidgetUpdateService));
                    refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, new[] { view.Item2 });
                    refreshIntent.PutExtra("ResourceId", layoutId);
                    view.Item1.SetOnClickPendingIntent(Resource.Id.RefreshButton, PendingIntent.GetService(ApplicationContext, 0, refreshIntent, 0));


                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }

            await Task.Delay(6000); //let the widget update in peace...
        }
        private void UpdateNowPlayingNotification()
        {
            Application.SynchronizationContext.Post(_ =>
            {
                try
                {
                    if (isNotifyPlayerActive)
                    {
                        var nm            = GetNotifyManager();
                        var remoteViewExp = new RemoteViews(PackageName, Resource.Layout.layout_notifi_player_exp);

                        remoteViewExp.SetImageViewResource(Resource.Id.ibNotifiAction3,
                                                           netStatus.StatusPlay == CmdHelper.NetStatus.Status.PAUSE
                                ? Resource.Drawable.play_100_black
                                : Resource.Drawable.pause_100_black);

                        Intent itAction = new Intent(BROAD_NOTIFY_PLAYER);
                        itAction.PutExtra("ACT", 0);
                        PendingIntent piAction = PendingIntent.GetBroadcast(this, IntentHelper.GetId(), itAction, 0);
                        remoteViewExp.SetOnClickPendingIntent(Resource.Id.ibNotifiAction1, piAction);

                        itAction = new Intent(BROAD_NOTIFY_PLAYER);
                        itAction.PutExtra("ACT", 1);
                        piAction = PendingIntent.GetBroadcast(this, IntentHelper.GetId(), itAction, 0);
                        remoteViewExp.SetOnClickPendingIntent(Resource.Id.ibNotifiAction2, piAction);

                        itAction = new Intent(BROAD_NOTIFY_PLAYER);
                        itAction.PutExtra("ACT", 2);
                        piAction = PendingIntent.GetBroadcast(this, IntentHelper.GetId(), itAction, 0);
                        remoteViewExp.SetOnClickPendingIntent(Resource.Id.ibNotifiAction3, piAction);

                        itAction = new Intent(BROAD_NOTIFY_PLAYER);
                        itAction.PutExtra("ACT", 3);
                        piAction = PendingIntent.GetBroadcast(this, IntentHelper.GetId(), itAction, 0);
                        remoteViewExp.SetOnClickPendingIntent(Resource.Id.ibNotifiAction4, piAction);

                        var titleName  = netTitleName?.TitleName;
                        var artistName = netArtistName?.ArtistName;

                        if (cmdInputState?.Parameter == "2E")
                        {
                            artistName = netTitleName?.TitleName;
                            titleName  = "Bluetooth";
                        }

                        if (titleName != null)
                        {
                            remoteViewExp.SetTextViewText(Resource.Id.tvNotifiTitle1, titleName);
                            remoteViewExp.SetViewVisibility(Resource.Id.tvNotifiTitle1, ViewStates.Visible);
                        }

                        if (artistName != null)
                        {
                            remoteViewExp.SetTextViewText(Resource.Id.tvNotifiTitle2, artistName);
                            remoteViewExp.SetViewVisibility(Resource.Id.tvNotifiTitle2, ViewStates.Visible);
                        }

                        if (netAlbumName?.AlbumName != null)
                        {
                            remoteViewExp.SetTextViewText(Resource.Id.tvNotifiTitle3, netAlbumName.AlbumName);
                            remoteViewExp.SetViewVisibility(Resource.Id.tvNotifiTitle3, ViewStates.Visible);
                        }

                        if (netArt?.bmArt != null)
                        {
                            remoteViewExp.SetImageViewBitmap(Resource.Id.ivNotifiCover, netArt.bmArt);
                            remoteViewExp.SetViewVisibility(Resource.Id.ivNotifiCover, ViewStates.Visible);
                        }
                        else
                        {
                            remoteViewExp.SetImageViewResource(Resource.Id.ivNotifiCover, Resource.Drawable.app_icon);
                            remoteViewExp.SetViewVisibility(Resource.Id.ivNotifiCover, ViewStates.Visible);
                        }

                        NotificationCompat.Builder nb = new NotificationCompat.Builder(ApplicationContext);


                        Intent intent = new Intent(this, typeof(HomeActivity));
                        intent.PutExtra(INTENT_HOME_TAB, 0);
                        intent.AddFlags(ActivityFlags.ClearTop);
                        intent.AddFlags(ActivityFlags.SingleTop);
                        PendingIntent pendingIntent = PendingIntent.GetActivity(this, IntentHelper.GetId(), intent, 0);
                        nb.SetContentIntent(pendingIntent);

                        nb.SetCustomBigContentView(remoteViewExp);
                        var x = remoteViewExp.Clone();
                        x.SetViewVisibility(Resource.Id.llNotifyExp, ViewStates.Gone);
                        nb.SetCustomContentView(x);

                        nb.SetSmallIcon(Resource.Drawable.av_receiver_100_black);
                        nb.SetOngoing(true);


                        nm.Notify(notifyIdPlayer, nb.Build());
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }, null);
        }
Esempio n. 19
0
        private void SetupRunningBtn (Context ctx, RemoteViews views)
        {
            var entry = new WidgetSyncManager.WidgetEntryData();
            var isRunning = false;

            // Check if an entry is running.
            foreach (var item in UpdateService.LastEntries)
                if (item.IsRunning) {
                    entry = item;
                    isRunning = true;
                }

            var baseTime = SystemClock.ElapsedRealtime ();

            if (isRunning) {
                views.SetInt (Resource.Id.WidgetActionButton, "setBackgroundColor", ctx.Resources.GetColor (Resource.Color.bright_red));
                views.SetInt (Resource.Id.WidgetActionButton, "setText", Resource.String.TimerStopButtonText);
                views.SetInt (Resource.Id.WidgetColorView, "setColorFilter", Color.ParseColor (entry.Color));
                views.SetViewVisibility (Resource.Id.WidgetRunningEntry, ViewStates.Visible);
                views.SetTextViewText (
                    Resource.Id.WidgetRunningDescriptionTextView,
                    String.IsNullOrWhiteSpace (entry.Description) ? ctx.Resources.GetString (Resource.String.RunningWidgetNoDescription) : entry.Description);

                var time = (long)entry.Duration.TotalMilliseconds;

                // Format chronometer correctly.
                string format = "00:%s";
                if (time >= 3600000 && time < 36000000) {
                    format = "0%s";
                } else if (time >= 36000000) {
                    format = "%s";
                }

                views.SetChronometer (Resource.Id.Chronometer, baseTime - (long)entry.Duration.TotalMilliseconds, format, true);
            } else {
                views.SetInt (Resource.Id.WidgetActionButton, "setBackgroundColor", ctx.Resources.GetColor (Resource.Color.bright_green));
                views.SetInt (Resource.Id.WidgetActionButton, "setText", Resource.String.TimerStartButtonText);
                views.SetViewVisibility (Resource.Id.WidgetRunningEntry, ViewStates.Invisible);
                views.SetChronometer (Resource.Id.Chronometer, baseTime, "00:%s", false);
                views.SetTextViewText (Resource.Id.Chronometer, "00:00:00");
            }
        }
Esempio n. 20
0
        public static void Update(Context context, NextAlarm nextAlarm, int[] appWidgetIds = null)
        {
            AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(context);
            ComponentName    thisWidget       = new ComponentName(context, Class.FromType(typeof(Widget)).Name);

            if (appWidgetIds == null)
            {
                appWidgetIds = appWidgetManager.GetAppWidgetIds(thisWidget);
            }
            var prefs = PrefsKeys.GetPrefs(context);

            foreach (var appWidgetId in appWidgetIds)
            {
                var timeOffset = prefs.GetInt(PrefsKeys.TimeOffset + appWidgetId, 0);
                nextAlarm.RefreshDisplay(context, timeOffset);

                RemoteViews updateViews = new RemoteViews(context.PackageName, Resource.Layout.widget);
                var         useTodDom   = prefs.GetBoolean(PrefsKeys.DateUseTodTom + appWidgetId, true);
                if (useTodDom)
                {
                    updateViews.SetTextViewText(Resource.Id.alarm_date, nextAlarm.DayAbbreviated);
                }
                else
                {
                    updateViews.SetTextViewText(Resource.Id.alarm_date, nextAlarm.Day);
                }
                if (nextAlarm.Time.Length > 5)
                {
                    updateViews.SetTextViewText(Resource.Id.alarm_time_12, nextAlarm.Time);
                    updateViews.SetViewVisibility(Resource.Id.alarm_time_12, ViewStates.Visible);
                    updateViews.SetViewVisibility(Resource.Id.alarm_time_24, ViewStates.Gone);
                }
                else
                {
                    updateViews.SetTextViewText(Resource.Id.alarm_time_24, nextAlarm.Time);
                    updateViews.SetViewVisibility(Resource.Id.alarm_time_24, ViewStates.Visible);
                    updateViews.SetViewVisibility(Resource.Id.alarm_time_12, ViewStates.Gone);
                }

                var dateColor = new Color(prefs.GetInt(PrefsKeys.DateColor + appWidgetId, context.GetCompatColor(Resource.Color.date)));
                updateViews.SetTextColor(Resource.Id.alarm_date, dateColor);
                var dateTextSize = prefs.GetInt(PrefsKeys.DateTextSize + appWidgetId, -1);
                if (dateTextSize != -1)
                {
                    updateViews.SetTextViewTextSize(Resource.Id.alarm_date, (int)ComplexUnitType.Dip, dateTextSize);
                }


                var timeColor = new Color(prefs.GetInt(PrefsKeys.TimeColor + appWidgetId, context.GetCompatColor(Resource.Color.time)));
                updateViews.SetTextColor(Resource.Id.alarm_time_24, timeColor);
                updateViews.SetTextColor(Resource.Id.alarm_time_12, timeColor);

                var timeTextSize = prefs.GetInt(PrefsKeys.TimeTextSize + appWidgetId, -1);
                if (timeTextSize != -1)
                {
                    updateViews.SetTextViewTextSize(Resource.Id.alarm_time_24, (int)ComplexUnitType.Dip, timeTextSize);
                    updateViews.SetTextViewTextSize(Resource.Id.alarm_time_12, (int)ComplexUnitType.Dip, timeTextSize);
                }

                var         iconColor    = new Color(prefs.GetInt(PrefsKeys.IconColor + appWidgetId, context.GetCompatColor(Resource.Color.icon)));
                Bitmap      sourceBitmap = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_alarm_white_18dp);
                Bitmap      resultBitmap = Bitmap.CreateBitmap(sourceBitmap.Width, sourceBitmap.Height, Bitmap.Config.Argb8888);
                Paint       p            = new Paint();
                float[]     matrix       = { 0, 0, 0, iconColor.R / 255f, 0,
                                             0,           0, 0, iconColor.G / 255f, 0,
                                             0,           0, 0, iconColor.B / 255f, 0,
                                             0,           0, 0, iconColor.A / 255f, 0 };
                ColorFilter filter = new ColorMatrixColorFilter(matrix);
                p.SetColorFilter(filter);
                Canvas canvas = new Canvas(resultBitmap);
                canvas.DrawBitmap(sourceBitmap, 0, 0, p);
                updateViews.SetImageViewBitmap(Resource.Id.alarm_icon, resultBitmap);

                var backgroundColor = new Color(prefs.GetInt(PrefsKeys.BackgroundColor + appWidgetId, context.GetCompatColor(Resource.Color.background)));
                updateViews.SetInt(Resource.Id.background, "setColorFilter", backgroundColor.ToArgb());
                updateViews.SetInt(Resource.Id.background, "setAlpha", backgroundColor.A);

                updateViews.SetOnClickPendingIntent(Resource.Id.widget_root, nextAlarm.RelayIntent);
                appWidgetManager.UpdateAppWidget(appWidgetId, updateViews);
            }

            ScheduleMidnightUpdate(context);
        }
        private void SetView(Context context, int appWidgetId, RemoteViews widgetView, WidgetLargeAltParams widgetLargeAltParams)
        {
            if (!widgetLargeAltParams.IsRefreshing)
            {
                Realm realm = Realm.GetInstance(DB.RealmConfiguration);

                // Bind the RemoteViewsService (adapter) for the Chapters list
                Intent intent = new Intent(context, typeof(RemoteChapterAdapter));
                intent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                intent.PutExtra(RemoteChapterAdapter.ExtraBookId, widgetLargeAltParams.Book);
                intent.PutExtra(RemoteChapterAdapter.ExtraSortOrder, widgetLargeAltParams.Descending);
                intent.SetData(Uri.Parse(intent.ToUri(IntentUriType.Scheme)));
                widgetView.SetRemoteAdapter(Resource.Id.list_chapters, intent);

                // Set Chapter list click intent template
                Intent        chapterClickIntentTemplate        = new Intent(Intent.ActionView);
                PendingIntent chapterClickPendingIntentTemplate = TaskStackBuilder.Create(context)
                                                                  .AddNextIntentWithParentStack(chapterClickIntentTemplate)
                                                                  .GetPendingIntent(appWidgetId, PendingIntentFlags.UpdateCurrent);
                widgetView.SetPendingIntentTemplate(Resource.Id.list_chapters, chapterClickPendingIntentTemplate);

                // Bind the click intent for the refresh button on the widget
                Intent refreshIntent = new Intent(context, typeof(WidgetLargeAlt));
                refreshIntent.SetAction(RefreshClick);
                refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                PendingIntent refreshPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, refreshIntent, PendingIntentFlags.UpdateCurrent);
                widgetView.SetOnClickPendingIntent(Resource.Id.btn_refresh, refreshPendingIntent);

                realm.Dispose();
            }

            if (widgetLargeAltParams.OpenMenu)
            {
                widgetView.SetViewVisibility(Resource.Id.menu, Android.Views.ViewStates.Visible);

                // Bind the click intent for the reverse button on the widget
                Intent CloseIntent = new Intent(context, typeof(WidgetLargeAlt));
                CloseIntent.SetAction(MenuOutsideClick);
                CloseIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                PendingIntent closePendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, CloseIntent, PendingIntentFlags.UpdateCurrent);
                widgetView.SetOnClickPendingIntent(Resource.Id.menu_outside, closePendingIntent);

                if (!widgetLargeAltParams.IsRefreshing)
                {
                    // Bind the RemoteViewsService (adapter) for the Book list
                    Intent intent = new Intent(context, typeof(RemoteBookAdapter));
                    intent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                    intent.PutExtra(RemoteBookAdapter.ExtraBookId, widgetLargeAltParams.Book);
                    intent.SetData(Uri.Parse(intent.ToUri(IntentUriType.Scheme)));
                    widgetView.SetRemoteAdapter(Resource.Id.list_books, intent);

                    // Set Book list click intent template
                    Intent        bookClickIntentTemplate        = new Intent(context, typeof(WidgetLargeAlt));
                    PendingIntent bookClickPendingIntentTemplate = PendingIntent.GetBroadcast(context, appWidgetId, bookClickIntentTemplate, PendingIntentFlags.UpdateCurrent);
                    widgetView.SetPendingIntentTemplate(Resource.Id.list_books, bookClickPendingIntentTemplate);
                }
            }
            else
            {
                widgetView.SetViewVisibility(Resource.Id.menu, Android.Views.ViewStates.Invisible);
            }

            // Bind the click intent for the menu button on the widget
            Intent menuIntent = new Intent(context, typeof(WidgetLargeAlt));

            menuIntent.SetAction(MenuClick);
            menuIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            PendingIntent menuPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, menuIntent, PendingIntentFlags.UpdateCurrent);

            widgetView.SetOnClickPendingIntent(Resource.Id.btn_menu, menuPendingIntent);

            // Bind the click intent for the reverse button on the widget
            Intent reverseIntent = new Intent(context, typeof(WidgetLargeAlt));

            reverseIntent.SetAction(ReverseClick);
            reverseIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            PendingIntent reversePendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, reverseIntent, PendingIntentFlags.UpdateCurrent);

            widgetView.SetOnClickPendingIntent(Resource.Id.btn_reverse, reversePendingIntent);
        }
Esempio n. 22
0
        // Build a widget update to show the current Wiktionary
        // "Word of the day." Will block until the online API returns.
        public RemoteViews BuildUpdate(Context context)
        {
            // var entry = WordEntry.GetWordOfTheDay();

            // Build an update that holds the updated widget contents
            var updateViews = new RemoteViews(context.PackageName, Resource.Layout.taskwidget);

            try
            {

                var launchAppIntent = new Intent(this, typeof (MainActivity));
                launchAppIntent.AddFlags(ActivityFlags.SingleTop);
                launchAppIntent.AddFlags(ActivityFlags.ClearTop);
                launchAppIntent.PutExtra("CameFromWidget", true);
                var pendingIntent = PendingIntent.GetActivity(context, 0, launchAppIntent, 0);
                updateViews.SetOnClickPendingIntent(Resource.Id.widget_top_action_bar, pendingIntent);

                var launchAppIntent2 = new Intent(this, typeof(MainActivity));
                launchAppIntent2.AddFlags(ActivityFlags.SingleTop);
                launchAppIntent2.AddFlags(ActivityFlags.ClearTop);
                var pendingIntent2 = PendingIntent.GetActivity(context, 0, launchAppIntent, 0);
                updateViews.SetOnClickPendingIntent(Resource.Id.widget_main_area, pendingIntent2);

                var newTasks = new List<string>();
                var newTasksChecked = new List<bool>();
                var lineVisibility = new List<ViewStates>();
                for(int i = 0; i < 15; i++)
                {
                    newTasks.Add(string.Empty);
                    newTasksChecked.Add(false);
                    lineVisibility.Add(ViewStates.Gone);
                }

                var tasks = DataManager.GetTasks(SortOption.Newest);
                var count = tasks.Count();
                count = count > m_TextViews.Length ? m_TextViews.Length : count;

                for (int i = 0; i < count; i++)
                {
                    var task = tasks.ElementAt(i);
                    newTasks[i] = task.Task;
                    newTasksChecked[i] = task.Checked;

                    if (i != 0)
                        lineVisibility[i - 1] = ViewStates.Visible;
                }

                if (newTasks[0] == string.Empty)
                        newTasks[0] = "No Tasks Added.";

                for(int i = 0; i < m_TextViews.Length; i++)
                {
                    updateViews.SetTextViewText(m_TextViews[i], newTasks[i]);
                    updateViews.SetTextColor(m_TextViews[i], newTasksChecked[i] ? Android.Graphics.Color.DarkGray : Android.Graphics.Color.Black );

                }

                for(int i = 0; i < m_TextViewsLines.Length; i++)
                    updateViews.SetViewVisibility(m_TextViewsLines[i], lineVisibility[i]);

            }
            catch (Exception ex)
            {

                updateViews.SetTextViewText(Resource.Id.widget_task_1, "Error loading widget");
            }

            return updateViews;
        }
Esempio n. 23
0
        private Notification BuildNotification()
        {
            _notificationBuilder = new NotificationCompat.Builder(ApplicationContext);
            _notificationBuilder.SetOngoing(true);
            _notificationBuilder.SetAutoCancel(false);
            _notificationBuilder.SetSmallIcon(Resource.Drawable.NotifIcon);
            //Open up the player screen when the user taps on the notification.
            var launchNowPlayingIntent = new Intent();
            launchNowPlayingIntent.SetAction(LaunchNowPlayingAction);
            var launchNowPlayingPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, launchNowPlayingIntent,
                0);
            _notificationBuilder.SetContentIntent(launchNowPlayingPendingIntent);

            //Grab the notification layouts.
            var notificationView = new RemoteViews(ApplicationContext.PackageName,
                Resource.Layout.notification_custom_layout);
            var expNotificationView = new RemoteViews(ApplicationContext.PackageName,
                Resource.Layout.notification_custom_expanded_layout);

            //Initialize the notification layout buttons.
            var previousTrackIntent = new Intent();
            previousTrackIntent.SetAction(PrevAction);
            var previousTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0,
                previousTrackIntent, 0);

            var playPauseTrackIntent = new Intent();
            playPauseTrackIntent.SetAction(PlayPauseAction);
            var playPauseTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0,
                playPauseTrackIntent, 0);

            var nextTrackIntent = new Intent();
            nextTrackIntent.SetAction(NextAction);
            var nextTrackPendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, nextTrackIntent, 0);

            var stopServiceIntent = new Intent();
            stopServiceIntent.SetAction(StopAction);
            var stopServicePendingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, stopServiceIntent,
                0);

            //Check if audio is playing and set the appropriate play/pause button.
            if (App.Current.AudioServiceConnection.GetPlaybackService().IsPlayingMusic)
            {
                notificationView.SetImageViewResource(Resource.Id.notification_base_play,
                    Resource.Drawable.btn_playback_pause_light);
                expNotificationView.SetImageViewResource(Resource.Id.notification_expanded_base_play,
                    Resource.Drawable.btn_playback_pause_light);
            }
            else
            {
                notificationView.SetImageViewResource(Resource.Id.notification_base_play,
                    Resource.Drawable.btn_playback_play_light);
                expNotificationView.SetImageViewResource(Resource.Id.notification_expanded_base_play,
                    Resource.Drawable.btn_playback_play_light);
            }

            var song = AudioPlayerHelper.CurrentQueueSong.Song;

            //Set the notification content.
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_one, song.Name);
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_two, song.ArtistName);
            expNotificationView.SetTextViewText(Resource.Id.notification_expanded_base_line_three, song.Album.Name);

            notificationView.SetTextViewText(Resource.Id.notification_base_line_one, song.Name);
            notificationView.SetTextViewText(Resource.Id.notification_base_line_two, song.ArtistName);

            //the previous and next buttons, always enabled.
            expNotificationView.SetViewVisibility(Resource.Id.notification_expanded_base_previous, ViewStates.Visible);
            expNotificationView.SetViewVisibility(Resource.Id.notification_expanded_base_next, ViewStates.Visible);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_play,
                playPauseTrackPendingIntent);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_next,
                nextTrackPendingIntent);
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_previous,
                previousTrackPendingIntent);

            notificationView.SetViewVisibility(Resource.Id.notification_base_previous, ViewStates.Visible);
            notificationView.SetViewVisibility(Resource.Id.notification_base_next, ViewStates.Visible);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_play, playPauseTrackPendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_next, nextTrackPendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_previous, previousTrackPendingIntent);

            //Set the "Stop Service" pending intents.
            expNotificationView.SetOnClickPendingIntent(Resource.Id.notification_expanded_base_collapse,
                stopServicePendingIntent);
            notificationView.SetOnClickPendingIntent(Resource.Id.notification_base_collapse, stopServicePendingIntent);

            //Set the album art.
            if (song.Album.Artwork != null)
            {
                if (song.Album.Artwork.Image != null)
                {
                    expNotificationView.SetImageViewBitmap(Resource.Id.notification_expanded_base_image,
                        song.Album.Artwork.Image as Bitmap);
                    notificationView.SetImageViewBitmap(Resource.Id.notification_base_image,
                        song.Album.Artwork.Image as Bitmap);
                }
                else
                    ((PclBitmapImage) song.Album.Artwork).PropertyChanged += OnPropertyChanged;
            }
            else
                song.Album.PropertyChanged += OnPropertyChanged;

            //Attach the shrunken layout to the notification.
            _notificationBuilder.SetContent(notificationView);

            //Build the notification object.
            var notification = _notificationBuilder.Build();

            //Attach the expanded layout to the notification and set its flags.
            notification.BigContentView = expNotificationView;
            notification.Flags = NotificationFlags.ForegroundService |
                                 NotificationFlags.NoClear |
                                 NotificationFlags.OngoingEvent;
            return notification;
        }
Esempio n. 24
0
        public override RemoteViews Setup(Context context, TimeEntryWidgetInfo widgetInfo)
        {
            var view = new RemoteViews(context.PackageName, Resource.Layout.TimeEntryWidget);

            SetupActionsForStartAndStopButtons(context, view);
            view.SetOnClickPendingIntent(Resource.Id.RootLayout, getOpenAppToLoginPendingIntent(context));

            if (widgetInfo.IsRunning)
            {
                view.SetViewVisibility(Resource.Id.StartButton, Gone);
                view.SetViewVisibility(Resource.Id.StopButton, Visible);

                var duration = (DateTimeOffset.Now - widgetInfo.StartTime).TotalMilliseconds;
                view.SetChronometer(Resource.Id.DurationTextView, SystemClock.ElapsedRealtime() - (long)duration, "%s", true);

                if (string.IsNullOrEmpty(widgetInfo.Description))
                {
                    view.SetTextViewText(Resource.Id.DescriptionTextView, Resources.NoDescription);
                    view.SetTextColor(Resource.Id.DescriptionTextView, context.SafeGetColor(Resource.Color.secondaryText));
                }
                else
                {
                    view.SetTextViewText(Resource.Id.DescriptionTextView, widgetInfo.Description);
                    view.SetTextColor(Resource.Id.DescriptionTextView, context.SafeGetColor(Resource.Color.primaryText));
                }

                view.SetViewVisibility(Resource.Id.DotView, widgetInfo.HasProject.ToVisibility());
                view.SetViewVisibility(Resource.Id.ProjectTextView, widgetInfo.HasProject.ToVisibility());
                if (widgetInfo.HasProject)
                {
                    // Project
                    var projectColor = widgetInfo.ProjectColor != null
                        ? Color.ParseColor(widgetInfo.ProjectColor)
                        : Color.Black;
                    view.SetInt(Resource.Id.DotView, "setBackgroundColor", projectColor);
                    view.SetTextViewText(Resource.Id.ProjectTextView, widgetInfo.ProjectName ?? "");
                    view.SetTextColor(Resource.Id.ProjectTextView, projectColor);

                    // Client
                    view.SetViewVisibility(Resource.Id.ClientTextView, widgetInfo.HasClient.ToVisibility());
                    if (widgetInfo.HasClient)
                        view.SetTextViewText(Resource.Id.ClientTextView, widgetInfo.ClientName);
                }
            }
            else
            {
                view.SetViewVisibility(Resource.Id.StartButton, Visible);
                view.SetViewVisibility(Resource.Id.StopButton, Gone);

                view.SetChronometer(Resource.Id.DurationTextView, SystemClock.ElapsedRealtime(), "%s", false);

                view.SetTextViewText(Resource.Id.DescriptionTextView, Resources.NoDescription);
                view.SetTextColor(Resource.Id.DescriptionTextView, context.SafeGetColor(Resource.Color.secondaryText));

                view.SetViewVisibility(Resource.Id.DotView, false.ToVisibility());
                view.SetViewVisibility(Resource.Id.ProjectTextView, false.ToVisibility());
                view.SetViewVisibility(Resource.Id.ClientTextView, false.ToVisibility());
            }

            return view;
        }
Esempio n. 25
0
        private void SetTextViewText(RemoteViews widgetView)
        {
            //    if (listTeamName.Count==0)
            //    {
            //        team1 = "1";
            //        team1points = "2";
            //    }
            //    else
            //    {
            //        //team1 = listTeamName[0];
            //        //team1points = listTeamPoints[0];
            //        team1 = "3";
            //        team1points = "4";
            //    }
            //team2 = MainActivity.listTeamName[1];
            //team2points = MainActivity.listTeamPoints[1];
            //team3 = MainActivity.listTeamName[2];
            //team3points = MainActivity.listTeamPoints[2];
            //team4 = MainActivity.listTeamName[3];
            //team4points = MainActivity.listTeamPoints[3];
            //team5 = MainActivity.listTeamName[4];
            //team5points = MainActivity.listTeamPoints[4];

            ////Typeface tf = Typeface.CreateFromAsset(Context, "epl.ttf");

            //widgetView.SetTextViewText(Resource.Id.widget_team1, string.Format(team1));
            //widgetView.SetTextViewText(Resource.Id.widget_team1points, string.Format(team1points));
            //widgetView.SetTextViewText(Resource.Id.widget_team2, string.Format(team2));
            //widgetView.SetTextViewText(Resource.Id.widget_team2points, string.Format(team2points));
            //widgetView.SetTextViewText(Resource.Id.widget_team3, string.Format(team3));
            //widgetView.SetTextViewText(Resource.Id.widget_team3points, string.Format(team3points));
            //widgetView.SetTextViewText(Resource.Id.widget_team4, string.Format(team4));
            //widgetView.SetTextViewText(Resource.Id.widget_team4points, string.Format(team4points));
            //widgetView.SetTextViewText(Resource.Id.widget_team5, string.Format(team5));
            //widgetView.SetTextViewText(Resource.Id.widget_team5points, string.Format(team5points));
            if (listTeamName.Count == 0)
            {
                widgetView.SetViewVisibility(Resource.Id.eplNeedRefresh, ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.eplTeamsGrid, ViewStates.Gone);
                //team1 = "Refresh Needed";
                //team1points = "6";
                //widgetView.SetTextViewText(Resource.Id.widget_team1, string.Format(team1));
                //widgetView.SetTextViewText(Resource.Id.widget_team1points, string.Format(team1points));
                widgetView.SetTextViewText(Resource.Id.updateTime, string.Format("Last updated on: Update Needed"));
            }
            else
            {
                widgetView.SetViewVisibility(Resource.Id.eplNeedRefresh, ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.eplTeamsGrid, ViewStates.Visible);
                team1       = listTeamName[0];
                team1points = listTeamPoints[0];
                team2       = listTeamName[1];
                team2points = listTeamPoints[1];
                team3       = listTeamName[2];
                team3points = listTeamPoints[2];
                team4       = listTeamName[3];
                team4points = listTeamPoints[3];
                team5       = listTeamName[4];
                team5points = listTeamPoints[4];
                widgetView.SetTextViewText(Resource.Id.widget_team1, string.Format(team1));
                widgetView.SetTextViewText(Resource.Id.widget_team1points, string.Format(team1points));
                widgetView.SetTextViewText(Resource.Id.widget_team2, string.Format(team2));
                widgetView.SetTextViewText(Resource.Id.widget_team2points, string.Format(team2points));
                widgetView.SetTextViewText(Resource.Id.widget_team3, string.Format(team3));
                widgetView.SetTextViewText(Resource.Id.widget_team3points, string.Format(team3points));
                widgetView.SetTextViewText(Resource.Id.widget_team4, string.Format(team4));
                widgetView.SetTextViewText(Resource.Id.widget_team4points, string.Format(team4points));
                widgetView.SetTextViewText(Resource.Id.widget_team5, string.Format(team5));
                widgetView.SetTextViewText(Resource.Id.widget_team5points, string.Format(team5points));
                widgetView.SetTextViewText(Resource.Id.updateTime, string.Format("Last updated on: {0:H:mm:ss}", DateTime.Now));
            }
        }
Esempio n. 26
0
        public static RemoteViews UpdateWidget(Context context, int appWidgetId, int[] appWidgetIds)
        {
            var remoteViews = new RemoteViews(context.PackageName, Resource.Layout.task_widget);

            var intent = new Intent(Intent.ActionMain);

            intent.AddCategory(Intent.CategoryLauncher);
            intent.SetComponent(new ComponentName(context, Java.Lang.Class.FromType(typeof(MainActivity))));

            var pending = PendingIntent.GetActivity(context, 0, intent, 0);

            remoteViews.SetOnClickPendingIntent(Resource.Id.widget_layout, pending);
            remoteViews.SetOnClickPendingIntent(Resource.Id.previous_button, GetPendingSelfIntent(context, ACTION_WIDGET_PREVIOUS));
            remoteViews.SetOnClickPendingIntent(Resource.Id.forward_button, GetPendingSelfIntent(context, ACTION_WIDGET_FORWARD));
            remoteViews.SetOnClickPendingIntent(Resource.Id.refresh_button, GetPendingSelfIntent(context, ACTION_WIDGET_REFRESH));

            var svcIntent = new Intent(context, typeof(TaskWidgetService));

            svcIntent.SetPackage(context.PackageName);
            svcIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            svcIntent.SetData(Android.Net.Uri.Parse(svcIntent.ToUri(IntentUriType.AndroidAppScheme)));

            var itemIntent = new Intent(context, typeof(TaskWidget));

            itemIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetIds);
            itemIntent.SetData(Android.Net.Uri.Parse(svcIntent.ToUri(IntentUriType.AndroidAppScheme)));
            itemIntent.SetAction(ACTION_WIDGET_LIST_ITEM);

            var itemPending = PendingIntent.GetBroadcast(context, 0, itemIntent, 0);

            remoteViews.SetPendingIntentTemplate(Resource.Id.task_listview, itemPending);

            var task = "";

            switch (CurrentTask)
            {
            case 0:
                task = context.GetText(Resource.String.daily_task);
                break;

            case 1:
                task = context.GetText(Resource.String.weekly_task);
                break;

            case 2:
                task = context.GetText(Resource.String.one_time_task);
                break;
            }

            remoteViews.SetInt(Resource.Id.widget_layout, "setBackgroundColor", (int)(Opacity * 0xFF) << 24 | Theme);
            // 어두운 테마
            if (Theme == Convert.ToInt32(0x000000))
            {
                remoteViews.SetTextColor(Resource.Id.task, Android.Graphics.Color.White);
                remoteViews.SetInt(Resource.Id.divider, "setBackgroundColor", Android.Graphics.Color.White);
            }
            // 밝은 테마
            else
            {
                remoteViews.SetTextColor(Resource.Id.task, Android.Graphics.Color.Black);
                remoteViews.SetInt(Resource.Id.divider, "setBackgroundColor", Android.Graphics.Color.Black);
            }
            remoteViews.SetTextViewText(Resource.Id.task, task);
            remoteViews.SetEmptyView(Resource.Id.task_listview, Resource.Id.empty_view);
            remoteViews.SetRemoteAdapter(Resource.Id.task_listview, svcIntent);
            if (Progress)
            {
                remoteViews.SetViewVisibility(Resource.Id.progress_layout, Android.Views.ViewStates.Visible);
            }
            else
            {
                remoteViews.SetViewVisibility(Resource.Id.progress_layout, Android.Views.ViewStates.Gone);
            }

            return(remoteViews);
        }
Esempio n. 27
0
        // Build a widget update to show the current Wiktionary
        // "Word of the day." Will block until the online API returns.
        public RemoteViews BuildUpdate(Context context)
        {
            // var entry = WordEntry.GetWordOfTheDay();

            // Build an update that holds the updated widget contents
            var updateViews = new RemoteViews(context.PackageName, Resource.Layout.taskwidget);

            try
            {
                var launchAppIntent = new Intent(this, typeof(MainActivity));
                launchAppIntent.AddFlags(ActivityFlags.SingleTop);
                launchAppIntent.AddFlags(ActivityFlags.ClearTop);
                launchAppIntent.PutExtra("CameFromWidget", true);
                var pendingIntent = PendingIntent.GetActivity(context, 0, launchAppIntent, 0);
                updateViews.SetOnClickPendingIntent(Resource.Id.widget_top_action_bar, pendingIntent);

                var launchAppIntent2 = new Intent(this, typeof(MainActivity));
                launchAppIntent2.AddFlags(ActivityFlags.SingleTop);
                launchAppIntent2.AddFlags(ActivityFlags.ClearTop);
                var pendingIntent2 = PendingIntent.GetActivity(context, 0, launchAppIntent, 0);
                updateViews.SetOnClickPendingIntent(Resource.Id.widget_main_area, pendingIntent2);


                var newTasks        = new List <string>();
                var newTasksChecked = new List <bool>();
                var lineVisibility  = new List <ViewStates>();
                for (int i = 0; i < 15; i++)
                {
                    newTasks.Add(string.Empty);
                    newTasksChecked.Add(false);
                    lineVisibility.Add(ViewStates.Gone);
                }


                var tasks = DataManager.GetTasks(SortOption.Newest);
                var count = tasks.Count();
                count = count > m_TextViews.Length ? m_TextViews.Length : count;

                for (int i = 0; i < count; i++)
                {
                    var task = tasks.ElementAt(i);
                    newTasks[i]        = task.Task;
                    newTasksChecked[i] = task.Checked;

                    if (i != 0)
                    {
                        lineVisibility[i - 1] = ViewStates.Visible;
                    }
                }

                if (newTasks[0] == string.Empty)
                {
                    newTasks[0] = "No Tasks Added.";
                }



                for (int i = 0; i < m_TextViews.Length; i++)
                {
                    updateViews.SetTextViewText(m_TextViews[i], newTasks[i]);
                    updateViews.SetTextColor(m_TextViews[i], newTasksChecked[i] ? Android.Graphics.Color.DarkGray : Android.Graphics.Color.Black);
                }

                for (int i = 0; i < m_TextViewsLines.Length; i++)
                {
                    updateViews.SetViewVisibility(m_TextViewsLines[i], lineVisibility[i]);
                }
            }
            catch (Exception ex)
            {
                updateViews.SetTextViewText(Resource.Id.widget_task_1, "Error loading widget");
            }


            return(updateViews);
        }