开发者

Call widget's onUpdate method from the app's main activity

I'm working on an Android application which includes a widget. The main interface of the app is a simple activity, but some of the things users can do in the activity make it necessary to update the widget - i.e. run its onUpdate method.

How can I trigger this metho开发者_StackOverflow社区d from the activity? Looking at other questions, I've been able to write code which changes its layout, but it doesn't seem to run onUpdate (since I'm just left with the empty layout and none of the data which is added during onUpdate).

Any ideas or code samples very much appreciated!


I am still pretty new to Android, but I accomplished this with three steps:

First, I put the contents of my AppWidgetProvider.onUpdate in a method (myUpdate(Context)).

Second, I overrode AppWidgetProvider.onReceive() to look something like this:

public void onReceive(final Context context, final Intent intent)
{
    super.onReceive(context, intent);

    if (MY_PUBLIC_STATIC_STRING.equals(intent.getAction()))
    {
        myUpdate(context);
    }
}

Third, from my other activity, I just send a generic broadcast with the action set on the intent.

Intent updateWidgetIntent = new Intent(context, MyWidget.class);
updateWidgetIntent.setAction(MyWidget.MY_PUBLIC_STATIC_STRING);
context.sendBroadcast(updateWidgetIntent);

This does have the down side of having to find the AppWidgetManager yourself from the context and the app widget ids, instead of the nice interface onUpdate gives you. So I am skeptical that this is the right approach. Best of luck.

myUpdate(Context) starts like this:

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds =
    appWidgetManager.getAppWidgetIds(new ComponentName(context, this.getClass()));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜