当app被杀死时,如何在xamarin中更新我的小部件?

时间:2017-01-16 13:44:02

标签: android xamarin service widget alarmmanager

我有一个扩展AppWidgetProvider的小部件。有一个按钮,通过点击它,用新数据更新小部件屏幕。当我杀死我的父应用程序时,小部件无法成功带来新数据。据我所知,我需要编写服务或报警管理器,以保持我的应用程序在后台运行。我应该在代码中实现这一点?我怎么能在xamarin中做到这一点? 我的代码是:

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

0 个答案:

没有答案