How can I update my widget in xamarin when app is killed?

romkatzromkatz ILMember ✭✭

I have widget which extends AppWidgetProvider. There is a button, by clicking on it, updates widget screen with a new data. When I kill my parent app, widget doesn't succeed to bring a new data. As I understood I need to write service or alarm manager in order to keep my app running in background. Where should I implement this in code? How can I do it in xamarin? My code is:

[BroadcastReceiver(Label = "@string/widget_name")]
[IntentFilter(new string[] { "android.appwidget.action.APPWIDGET_UPDATE" })]
[MetaData("android.appwidget.provider", Resource = "@xml/widget_word")]
public class WidgetProvider : AppWidgetProvider
{
    public static string UPDATE_LIST = "UPDATE_LIST";
    public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
    {
        base.OnUpdate(context, appWidgetManager, appWidgetIds);

        ComponentName thiswidget = new ComponentName(context, Java.Lang.Class.FromType(typeof(WidgetProvider)).Name);
        int[] allWidgetsIds = appWidgetManager.GetAppWidgetIds(thiswidget);

        for (int i = 0; i < allWidgetsIds.Length; i++)
        {

            RemoteViews remoteViews = new RemoteViews(context.PackageName, Resource.Layout.widget_layout);
            Intent svcIntent = new Intent(context, typeof(WidgetService));
            svcIntent.SetPackage(context.PackageName);
            svcIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, allWidgetsIds[i]);
            remoteViews.SetRemoteAdapter(Resource.Id.listViewWidget, svcIntent);


            Intent intent = new Intent(context, typeof(WidgetProvider));
            intent.SetAction(AppWidgetManager.ActionAppwidgetUpdate);
            intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, appWidgetIds[i]);


            PendingIntent pi = PendingIntent.GetBroadcast(context, 0, intent, PendingIntentFlags.UpdateCurrent);
            remoteViews.SetOnClickPendingIntent(Resource.Id.btnupdate, pi);

            appWidgetManager.UpdateAppWidget(allWidgetsIds[i], remoteViews);
        }
    }

    public override void OnReceive(Context context, Intent intent)
    {
        base.OnReceive(context, intent);
        if (intent.Action.Equals(AppWidgetManager.ActionAppwidgetUpdate))
        {
            updateWidget(context);                
        }
    }
    private void updateWidget(Context context)
    {
        AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(context);
        int[] appWidgetids = appWidgetManager.GetAppWidgetIds(new ComponentName(context, Java.Lang.Class.FromType(typeof(WidgetProvider)).Name));
        appWidgetManager.NotifyAppWidgetViewDataChanged(appWidgetids, Resource.Id.listViewWidget);
    }
}
Sign In or Register to comment.