Button click event for android widget

后端 未结 5 1210
醉酒成梦
醉酒成梦 2021-01-30 13:16

I have an android widget that fetches data from a server every 10 minutes and display\'s it on the screen.
I\'d like to add a \"Refresh\" button to that widget.
When th

5条回答
  •  梦谈多话
    2021-01-30 13:47

    Here is one example more that should help:

    package com.automatic.widget;
    
    import android.app.PendingIntent;
    import android.appwidget.AppWidgetManager;
    import android.appwidget.AppWidgetProvider;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.RemoteViews;
    
    public class Widget extends AppWidgetProvider {
    
        private static final String SYNC_CLICKED    = "automaticWidgetSyncButtonClick";
    
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            RemoteViews remoteViews;
            ComponentName watchWidget;
    
            remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            watchWidget = new ComponentName(context, Widget.class);
    
            remoteViews.setOnClickPendingIntent(R.id.sync_button, getPendingSelfIntent(context, SYNC_CLICKED));
            appWidgetManager.updateAppWidget(watchWidget, remoteViews);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            super.onReceive(context, intent);
    
            if (SYNC_CLICKED.equals(intent.getAction())) {
    
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    
                RemoteViews remoteViews;
                ComponentName watchWidget;
    
                remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
                watchWidget = new ComponentName(context, Widget.class);
    
                remoteViews.setTextViewText(R.id.sync_button, "TESTING");
    
                appWidgetManager.updateAppWidget(watchWidget, remoteViews);
    
            }
        }
    
        protected PendingIntent getPendingSelfIntent(Context context, String action) {
            Intent intent = new Intent(context, getClass());
            intent.setAction(action);
            return PendingIntent.getBroadcast(context, 0, intent, 0);
        }
    }
    

提交回复
热议问题