I have made a Xamarin.Android Widget with a Button and TextView.
Currently, the widget does not update the TextView when the Button is pressed when the app is not open. However, if the app is in the background, then pressing the Button will update the TextView.
public class WidgetClass : AppWidgetProvider, IUpdateDataService
{
public static String SaveClick = "Save Product";
public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
var me = new ComponentName(context, Java.Lang.Class.FromType(typeof(WidgetClass)).Name);
appWidgetManager.UpdateAppWidget(me, BuildRemoteViews(context, appWidgetIds));
}
private RemoteViews BuildRemoteViews(Context context, int[] appWidgetIds)
{
var widgetView = new RemoteViews(context.PackageName, Resource.Layout.widget);
UpdateData(widgetView);
RegisterClicks(context, appWidgetIds, widgetView);
return widgetView;
}
private void UpdateData(RemoteViews widgetView)
{
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
widgetView.SetTextViewText(Resource.Id.textView1, "Last Product: " + App.latestProduct.ProductSaveTime.ToString("g", currentCulture));
}
private void RegisterClicks(Context context, int[] appWidgetIds, RemoteViews widgetView)
{
var intent = new Intent(context, typeof(WidgetClass));
intent.SetAction(AppWidgetManager.ActionAppwidgetUpdate);
intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, appWidgetIds);
widgetView.SetOnClickPendingIntent(Resource.Id.buttonSave, GetPendingSelfIntent(context, SaveClick));
}
private PendingIntent GetPendingSelfIntent(Context context, string action)
{
var intent = new Intent(context, typeof(WidgetClass));
intent.SetAction(action);
return PendingIntent.GetBroadcast(context, 0, intent, 0);
}
public override void OnReceive(Context context, Intent intent)
{
base.OnReceive(context, intent);
if (SaveClick.Equals(intent.Action))
{
Product product = new Product
{
ProductSaveTime = DateTime.Now
};
App.latestProduct = product;
RemoteViews remoteViews = new RemoteViews(context.PackageName, Resource.Layout.widget);
UpdateData(remoteViews);
AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(context);
ComponentName componentName = new ComponentName(context, Java.Lang.Class.FromType(typeof(WidgetClass)).Name);
appWidgetManager.UpdateAppWidget(componentName, remoteViews);
}
}
public void UpdateWidgetUI()
{
var widgetView = new RemoteViews(MainActivity.Instance.PackageName, Resource.Layout.widget);
UpdateData(widgetView);
AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(MainActivity.Instance);
ComponentName componentName = new ComponentName(MainActivity.Instance, Java.Lang.Class.FromType(typeof(WidgetClass)).Name);
appWidgetManager.UpdateAppWidget(componentName, widgetView);
}
}
App.cs:
public static Product latestProduct;
Is it possible to make the Button function when the app is not running?