【问题标题】:How can i update a widget only when i press a button in an activity from within the main app仅当我在主应用程序中按下活动中的按钮时,如何更新小部件
【发布时间】:2015-04-29 06:43:46
【问题描述】:

我制作了一个包含 5 个活动的应用程序。我只是想知道只有当我在主应用程序的活动中按下当前按钮时才能更新小部件

【问题讨论】:

    标签: android android-activity android-widget


    【解决方案1】:

    您需要一个reciever 用于在 manifest.xml 中声明的小部件:

        <receiver
            android:label="MyIP Widget"
            android:icon="@drawable/ic_launcher"
            android:name="Widget" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/example_appwidget_info" />
        </receiver>
    

    该块应该在应用程序块内。

    在我的示例中,小部件会在连接状态更改时更新。您可以将其替换为自定义意图。而且,从您的活动中,您需要发送该意图来更新小部件,如下所示:

      Intent i = new Intent();
      i.setAction(CUSTOM_INTENT);
      context.sendBroadcast(i);
    

    在哪里

    public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";
    

    你可以选择你想要的名字。

    并确保在接收器中添加相同的名称:

    <action android:name="jason.wei.custom.intent.action.TEST" />
    

    更新: 要接收您的广播,您需要在 Widget 类中使用此方法

    public class Widget extends AppWidgetProvider {
    
    ...
    
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context,intent);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
        ComponentName thisWidget = new ComponentName(context.getApplicationContext(), Widget.class);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        if (appWidgetIds != null && appWidgetIds.length > 0) {
            onUpdate(context, appWidgetManager, appWidgetIds);
        }
    }
    

    上面的代码可能看起来有点复杂,但它需要更新您的小部件的所有实例(用户可能在不同的主屏幕上或什至在一个屏幕上拥有您的小部件)。

    如您所见,它调用 onUpdate 方法,您可以在其中设置要执行的操作以更新小部件:

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);    
    //your update code here
    }
    

    【讨论】:

    • 我怎样才能在小部件类中收到这个广播,你能帮我吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    相关资源
    最近更新 更多