如何创建一个具有配置活动的应用小部件,并进行首次更新?

22

这真是让我疯狂了。即使按照推荐的做法,我也不知道如何从配置活动更新应用程序小部件。对于为什么在应用程序小部件创建时未调用更新方法,我无法理解。

我的需求是:一个包含项目集合(带有列表视图)的应用程序小部件。但用户需要选择某些内容,因此我需要一个配置活动。

配置活动是一个ListActivity

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ChecksWidgetConfigureActivity extends SherlockListActivity {
    private List<Long> mRowIDs;
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private BaseAdapter mAdapter;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_CANCELED);
        setContentView(R.layout.checks_widget_configure);

        final Intent intent = getIntent();
        final Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        mRowIDs = new ArrayList<Long>(); // it's actually loaded from an ASyncTask, don't worry about that — it works.
        mAdapter = new MyListAdapter((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE));
        getListView().setAdapter(mAdapter);
    }

    private class MyListAdapter extends BaseAdapter {
        // not relevant...
    }

    @Override
    protected void onListItemClick(final ListView l, final View v, final int position, final long id) {
        if (position < mRowIDs.size()) {
            // Set widget result
            final Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            resultValue.putExtra("rowId", mRowIDs.get(position));
            setResult(RESULT_OK, resultValue);

            // Request widget update
            final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
            ChecksWidgetProvider.updateAppWidget(this, appWidgetManager, mAppWidgetId, mRowIDs);
        }

        finish();
    }
}

正如您所看到的,我从我的应用程序小部件提供程序中调用了一个静态方法。我得到这个想法来自于官方文档

让我们来看看我的提供程序:

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class ChecksWidgetProvider extends AppWidgetProvider {
    public static final String TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION";
    public static final String EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM";

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

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i = 0; i < N; i++) {
            // Here we setup the intent which points to the StackViewService which will
            // provide the views for this collection.
            final Intent intent = new Intent(context, ChecksWidgetService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            // When intents are compared, the extras are ignored, so we need to embed the extras
            // into the data so that the extras will not be ignored.
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.checks_widget);
            rv.setRemoteAdapter(android.R.id.list, intent);

            // The empty view is displayed when the collection has no items. It should be a sibling
            // of the collection view.
            rv.setEmptyView(android.R.id.list, android.R.id.empty);

            // Here we setup the a pending intent template. Individuals items of a collection
            // cannot setup their own pending intents, instead, the collection as a whole can
            // setup a pending intent template, and the individual items can set a fillInIntent
            // to create unique before on an item to item basis.
            final Intent toastIntent = new Intent(context, ChecksWidgetProvider.class);
            toastIntent.setAction(ChecksWidgetProvider.TOAST_ACTION);
            toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            toastIntent.setData(Uri.parse(toastIntent.toUri(Intent.URI_INTENT_SCHEME)));
            final PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            rv.setPendingIntentTemplate(android.R.id.list, toastPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
        }
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        if (intent.getAction().equals(TOAST_ACTION)) {
            final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            final long rowId = intent.getLongExtra("rowId", 0);
            final int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);
            Toast.makeText(context, "Touched view " + viewIndex + " (rowId: " + rowId + ")", Toast.LENGTH_SHORT).show();
        }
        super.onReceive(context, intent);
    }

    @Override
    public void onAppWidgetOptionsChanged(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final Bundle newOptions) {
        updateAppWidget(context, appWidgetManager, appWidgetId, newOptions.getLong("rowId"));
    }

    public static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final long rowId) {
        final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.checks_widget);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}
这基本上是官方文档的复制粘贴。我们可以在这里看到我的静态方法。暂时假设它实际上使用了rowId。 当我收到选项更改广播(onAppWidgetOptionsChanged)时,我们还可以看到另一个失败的尝试更新应用程序小部件。 基于集合的应用程序小部件所需的Service几乎是官方文档的完全复制/粘贴:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ChecksWidgetService extends RemoteViewsService {
    @Override
    public RemoteViewsFactory onGetViewFactory(final Intent intent) {
        return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
    }
}

class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
    private static final int mCount = 10;
    private final List<WidgetItem> mWidgetItems = new ArrayList<WidgetItem>();
    private final Context mContext;
    private final int mAppWidgetId;
    private final long mRowId;

    public StackRemoteViewsFactory(final Context context, final Intent intent) {
        mContext = context;
        mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        mRowId = intent.getLongExtra("rowId", 0);
    }

    @Override
    public void onCreate() {
        // In onCreate() you setup any connections / cursors to your data source. Heavy lifting,
        // for example downloading or creating content etc, should be deferred to onDataSetChanged()
        // or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.
        for (int i = 0; i < mCount; i++) {
            mWidgetItems.add(new WidgetItem(i + " (rowId: " + mRowId + ") !"));
        }

        // We sleep for 3 seconds here to show how the empty view appears in the interim.
        // The empty view is set in the StackWidgetProvider and should be a sibling of the
        // collection view.
        try {
            Thread.sleep(3000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        // In onDestroy() you should tear down anything that was setup for your data source,
        // eg. cursors, connections, etc.
        mWidgetItems.clear();
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public RemoteViews getViewAt(final int position) {
        // position will always range from 0 to getCount() - 1.

        // We construct a remote views item based on our widget item xml file, and set the
        // text based on the position.
        final RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
        rv.setTextViewText(R.id.widget_item, mWidgetItems.get(position).text);

        // Next, we set a fill-intent which will be used to fill-in the pending intent template
        // which is set on the collection view in StackWidgetProvider.
        final Bundle extras = new Bundle();
        extras.putInt(ChecksWidgetProvider.EXTRA_ITEM, position);
        final Intent fillInIntent = new Intent();
        fillInIntent.putExtras(extras);
        rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent);

        // You can do heaving lifting in here, synchronously. For example, if you need to
        // process an image, fetch something from the network, etc., it is ok to do it here,
        // synchronously. A loading view will show up in lieu of the actual contents in the
        // interim.
        try {
            L.d("Loading view " + position);
            Thread.sleep(500);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }

        // Return the remote views object.
        return rv;
    }

    @Override
    public RemoteViews getLoadingView() {
        // You can create a custom loading view (for instance when getViewAt() is slow.) If you
        // return null here, you will get the default loading view.
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public long getItemId(final int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public void onDataSetChanged() {
        // This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
        // on the collection view corresponding to this factory. You can do heaving lifting in
        // here, synchronously. For example, if you need to process an image, fetch something
        // from the network, etc., it is ok to do it here, synchronously. The widget will remain
        // in its current state while work is being done here, so you don't need to worry about
        // locking up the widget.
    }
}
最后,我的小部件布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widgetLayout"
    android:orientation="vertical"
    android:padding="@dimen/widget_margin"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/resizeable_widget_title"
        style="@style/show_subTitle"
        android:padding="2dp"
        android:paddingLeft="5dp"
        android:textColor="#FFFFFFFF"
        android:background="@drawable/background_pink_striked_transparent"
        android:text="@string/show_title_key_dates" />

    <ListView
        android:id="@android:id/list"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:background="@color/timeline_month_dark"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:text="@string/empty_view_text"
        android:textSize="20sp" />

</LinearLayout>

我的安卓清单 XML 文件中相关的部分:

<receiver android:name="com.my.full.pkg.ChecksWidgetProvider">
    <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>

    <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/checks_widget_info" />
</receiver>
<activity android:name="com.my.full.pkg.ChecksWidgetConfigureActivity">
    <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
    </intent-filter>
</activity>
<service
    android:name="com.my.full.pkg.ChecksWidgetService"
    android:permission="android.permission.BIND_REMOTEVIEWS" />

xml/checks_widget_info.xml:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:minHeight="146dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/checks_widget"
    android:configure="com.my.full.pkg.ChecksWidgetConfigureActivity"
    android:resizeMode="horizontal|vertical"
    android:previewImage="@drawable/resizeable_widget_preview" />
那么,问题出在哪里呢?当我创建这个小部件时,它是空的。我是指完全没有东西。我的布局中没有定义空视图!这是怎么回事? 如果我重新安装应用程序或重启设备(或杀死启动器应用程序),则应用程序小部件实际上会更新并包含自动添加的10个项目,就像示例中一样。 我无法让该死的东西在配置活动完成后更新。摘自文档的这个句子已超出了我的理解范围:“当创建App Widget时,将不调用onUpdate()方法[...]——仅在第一次跳过。”。 我的问题是: 1. 为什么Android开发团队选择在创建小部件时不调用更新? 2. 我如何在配置活动完成之前更新我的应用程序小部件? 我还不明白的另一件事是操作流程: 1. 安装具有最新编译代码的应用程序,在启动器上准备好空间,从启动器打开“窗口小部件”菜单 2. 选择我的小部件并将其放置在所需区域 3. 此时,我的应用程序小部件提供程序接收到android.appwidget.action.APPWIDGET_ENABLED,然后是android.appwidget.action.APPWIDGET_UPDATE 4. 然后,我的应用程序小部件提供程序调用其onUpdate方法。我期望这会在配置活动完成后发生... 5. 我的配置活动开始。但是,应用程序小部件似乎已经创建并更新了,这一点我不理解。 6. 我从配置活动中选择项:onListItemClick被调用 7. 我的提供程序中的静态updateAppWidget被调用,绝望地试图更新小部件。 8. 配置活动设置其结果并完成。 9. 提供程序接收到android.appwidget.action.APPWIDGET_UPDATE_OPTIONS:当创建时接收大小更新确实有很多意义。那就是我绝望地调用updateAppWidget的地方 10.我的提供程序中的onUpdate未被调用。为什么?! 最后:该小部件为空。不是listview-empty或@ android:id / empty-empty,而是真正的空。没有显示任何视图。什么也没有。
如果我再次安装应用程序,则应用程序小部件将像预期的那样填充带有列表视图内的视图。
调整小部件大小没有效果。它只是再次调用onAppWidgetOptionsChanged,这没有任何效果。 我所说的空白:应用程序小部件布局被充气,但是listview未被充气,并且未显示空视图。

我没有看到你的小部件配置XML和AndroidManifest.xml文件,你能提供它们吗? - Andrii Chernenko
我已经添加了AndroidManifest.xml相关的部分,很快我会添加小部件配置XML(它现在还没有在源存储库中,所以几个小时内我将无法访问源代码)。 - Benoit Duffez
3个回答

34
用AppWidgetManager更新的缺点是你必须提供RemoteViews,这从设计角度来看是不合理的,因为与RemoteViews相关的逻辑应该封装在AppWidgetProvider中(或在您的情况下是RemoteViewsService.RemoteViewsFactory中)。 SciencyGuy通过公开静态方法来暴露RemoteViews逻辑是解决这个问题的一种方式,但有一种更优雅的解决方案就是直接向小部件发送广播。
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, ChecksWidgetProvider.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {mAppWidgetId});
sendBroadcast(intent);
作为结果,AppWidgetProvider的onUpdate()方法将被调用以创建小部件的RemoteViews。

请在接受答案之前尝试这个答案,因为已接受的答案由于某些不同的逻辑而引入了一些错误。这是我在配置活动后使用的方法,它非常有效。 - Henrique de Sousa
1
FYI,@HenriqueSousa提到的“accepted”答案是指他写作时Jonas的答案。我今天刚标记了Emanuel的答案为被接受的答案。 - Benoit Duffez
使用这种方法要小心 - 在此处查看我遇到的问题here,以及解决方案。简单来说,文档是误导性的 - 只要活动返回RESULT_OK和包含小部件ID的意图,onUpdate()将在配置活动完成时调用。 - rothloup
@rothloup,你遇到了不同的问题,但并不是因为这种方法是错误的。它只是用一种更优雅的解决方案替换了https://developer.android0com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration中的创建RemoteView部分。请参见我对你所引用的问题的答案。 - Emanuel Moecklin
非常感谢,官方文档 实在是太不完整了。对于任何未来的读者,EXTRA_APPWIDGET_ID 是无效的,必须使用 EXTRA_APPWIDGET_IDS - olfek

16

你说得对,配置活动完成后不会触发 onUpdate 方法。这取决于你的配置活动来进行初始更新。因此,你需要构建初始视图。

这就是在配置结束时应该做的要点:

// First set result OK with appropriate widgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK, resultValue);

// Build/Update widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());

// This is equivalent to your ChecksWidgetProvider.updateAppWidget()    
appWidgetManager.updateAppWidget(appWidgetId,
                                 ChecksWidgetProvider.buildRemoteViews(getApplicationContext(),
                                                                       appWidgetId));

// Updates the collection view, not necessary the first time
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.notes_list);

// Destroy activity
finish();

您已经正确设置了结果。并且您调用了ChecksWidgetProvider.updateAppWidget(),但是updateAppWidget()没有返回正确的结果。

当前的updateAppWidget()返回一个空的RemoteViews对象,这就解释了为什么您的小部件一开始是完全空白的。您还没有将视图填充到任何内容中。我建议您将代码从onUpdate移动到一个静态的buildRemoteViews()方法中,您可以从onUpdate和updateAppWidget()中调用该方法:

public static RemoteViews buildRemoteViews(final Context context, final int appWidgetId) {
        final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.checks_widget);
        rv.setRemoteAdapter(android.R.id.list, intent);

        // The empty view is displayed when the collection has no items. It should be a sibling
        // of the collection view.
        rv.setEmptyView(android.R.id.list, android.R.id.empty);

        // Here we setup the a pending intent template. Individuals items of a collection
        // cannot setup their own pending intents, instead, the collection as a whole can
        // setup a pending intent template, and the individual items can set a fillInIntent
        // to create unique before on an item to item basis.
        final Intent toastIntent = new Intent(context, ChecksWidgetProvider.class);
        toastIntent.setAction(ChecksWidgetProvider.TOAST_ACTION);
        toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        toastIntent.setData(Uri.parse(toastIntent.toUri(Intent.URI_INTENT_SCHEME)));
        final PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        rv.setPendingIntentTemplate(android.R.id.list, toastPendingIntent);

        return rv;
}

public static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) {
    final RemoteViews views = buildRemoteViews(context, appWidgetId);
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

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

    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int appWidgetId: appWidgetIds) {
        RemoteViews rv = buildRemoteViews(context, appWidgetId);
        appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
    }
}

这应该可以处理小部件的初始化。

在我的示例代码中,在调用finish()之前的最后一步是更新收藏视图。正如注释所说,第一次不一定需要这样做。但是,我包括它以防万一您想允许在添加小部件后重新配置小部件。在那种情况下,必须手动更新收藏视图,以确保加载适当的视图和数据。


太棒了!太聪明了!我想我在文档方面有点迷失。再次感谢。 - Benoit Duffez

2
我没有看到你的appwidgetprovider.xml和AndroidManifest.xml,但我的猜测是你没有正确设置配置活动。

以下是正确的操作步骤:

  1. add the following attribute to your appwidgetprovider.xml:

    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
        ...
        android:configure="com.full.package.name.ChecksWidgetConfigureActivity" 
        ... />
    
  2. Your configuration activity should have an appropriate intent-filter:

    <activity android:name=".ChecksWidgetConfigureActivity">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
        </intent-filter>
    </activity>
    
如果配置活动被正确配置,onUpdate()会在其完成后触发。

如果那个没有正确配置,我的配置活动不会出现,对吧?我已经在问题中更新了我的清单条目。 - Benoit Duffez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,