Please help with very simple android widget button click. Getting very frustrated. :(

后端 未结 2 1630
野趣味
野趣味 2021-01-13 14:21

I have poured over every example that I can find and I have gone through the official documentation from google. All I am trying to do is create a toast notification from a

相关标签:
2条回答
  • 2021-01-13 14:34

    As bigstones wrote, you need to use broadcast. Sample code:

    protected PendingIntent getPendingSelfIntent(Context context, String action) {
        Intent intent = new Intent(context, getClass());
        intent.setAction(action);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }
    
    views.setOnClickPendingIntent(R.id.Timm, getPendingSelfIntent(context,
                                  "ham"));
    
    0 讨论(0)
  • 2021-01-13 14:55

    here is full version:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题