简体   繁体   中英

How to obtain removeView for a given appWidgetId in onReceive

Recently, I had built up my widget UI, and install click event handler in onUpdate .

I was wondering, what is the proper way for me to access remoteView , for a given appWidgetId , during onReceive ? Is storing all removeView s in a local member map like

Map<appWidgetId, remoteView>

a good idea? Or, is there any better way?


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class MyAppWidgetProvider extends AppWidgetProvider {    
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout_inverse_holo_light);

            // Register an onClickListener
            Intent refreshIntent = new Intent(context, JStockAppWidgetProvider.class);
            refreshIntent.setAction(REFRESH_ACTION);
            refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);            
            remoteViews.setOnClickPendingIntent(R.id.refresh_button, refreshPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        if (intent.getAction().equals(REFRESH_ACTION)) {
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

            // How can I access my remoteView?
            // During onUpdate, is saving all the remoteViews in local member
            // Map<appWidgetId, remoteView> a good idea?
        }
        super.onReceive(context, intent);
    }

    private static final String REFRESH_ACTION = "org.yccheok.jstock.gui.widget.JStockAppWidgetProvider.REFRESH_ACTION";  
}

If you want to refresh the widget, just create a new RemoteView, and then call

appWidgetManager.updateAppWidget

Or if your widget is backed by a CursorAdaptor of some sort, you should implement

RemoteViewsService.RemoteViewsFactory

Any changes to the adaptor will then automatically updates the widget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM