如何在小部件中使用Eventbus?

时间:2016-09-17 10:43:24

标签: android widget greenrobot-eventbus appwidgetprovider

我正在试图弄清楚如何在AppWidgetProvider中使用Greenbot Eventbus库。我尝试了以下,但不起作用:

public class SimpleWidgetProvider extends AppWidgetProvider {
    RemoteViews remoteViews;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int count = appWidgetIds.length;

        for (int i = 0; i < count; i++) {
            int widgetId = appWidgetIds[i];
            remoteViews = new RemoteViews(context.getPackageName(), R.layout.simple_widget);
            //set image
            remoteViews.setImageViewResource(R.id.piggy_bank, R.drawable.piggy_bank);

            Intent intent = new Intent(context, SimpleWidgetProvider.class);
            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            //set refresh button
            remoteViews.setOnClickPendingIntent(R.id.refresh_btn, pendingIntent);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        EventBus.getDefault().register(this);
    }

    //set total price
    @Subscribe
    public void onPriceEvent(TotalPriceEvent event) {
        double price = event.totalPrice;
        remoteViews.setTextViewText(R.id.total_amount, String.valueOf(price));
    }

    @Override
    public void onDisabled(Context context) {
        EventBus.getDefault().unregister(this);
        super.onDisabled(context);
    }
}

如果我需要附加更多代码,请告诉我。

1 个答案:

答案 0 :(得分:3)

AppWidgetProvider只是BroadcastReceiver,具有专门的onReceive()方法,可根据操作将广播委托给其他方法。清单注册BroadcastReceiver的实例并不意味着存活很长时间。它们运行的​​时间足够长,可以处理广播然后死掉,所以订阅事件总线并不会按预期工作,并且考虑到重叠模式,它们有点无意义。如果您想通知您的SimpleWidgetProvider某事,只需向其发送广播。

例如,我们为SimpleWidgetProvider类定义自己的操作,并在onReceive()方法中检查它。如果是我们的,我们将根据需要处理它,否则调用super方法以允许AppWidgetProvider正确委派它。

public class SimpleWidgetProvider extends AppWidgetProvider {
    public static final String MY_SPECIAL_ACTION = "com.mycompany.myapp.SPECIAL_ACTION";

    @Override
    public void onReceive(Context context, Intent intent) {
        if(MY_SPECIAL_ACTION.equals(intent.getAction())) {
            // Do your thing
        }
        else {
            // Not our action, so let AppWidgetProvider handle it
            super.onReceive(context, intent);
        }
    }
    ...
}

我们可以使用通常的机制向其发送广播。

Intent widgetNotify = new Intent(context, SimpleWidgetProvider.class);
widgetNotify.setAction(SimpleWidgetProvider.MY_SPECIAL_ACTION);
widgetNotify.putExtra(...);
...
context.sendBroadcast(widgetNotify);

我还要提到superonEnabled()中的onDisabled()来电是不必要的,因为这些方法在AppWidgetProvider中是空的。