1

我正在编写一个使用 PreferenceActivity 配置的小部件。小部件需要配置一次 - 它依赖于使用 oauth 身份验证的 api。流程如下:

  1. 将小部件拖动到主屏幕
  2. PreferenceActivity 出现,请求一个请求令牌并重定向到浏览器
  3. 用户通过网站进行身份验证,然后我有一个回调到 PreferenceActivty
  4. 小部件请求访问令牌并保存它
  5. Widget 刷新并关闭 PreferenceActivty

问题出在第 5 步 - 关闭发生,但小部件未添加到主屏幕!问题是,如果我执行此过程,然后将另一个小部件添加到主屏幕,代码会看到我们已经通过身份验证,它会调用相同的函数来刷新/关闭 PreferenceActivity。这次它起作用并被添加到主屏幕!

我无法弄清楚问题出在哪里。我确实使用普通的 Activity 而不是 PreferenceActivity 进行了这项工作,但我不明白为什么这会是一个问题。当 PreferenceActivity 结束以在步骤 2 中启动浏览器时,我想我应该调用 setResult(RESULT_OK...),但它不起作用。我想是因为它可以通过 onCreate 工作,但不能通过回调(当 asynctask 完成时)工作,这是因为它没有在 UI 线程上运行,但是通过调用 runOnUiThread 来强制它也不起作用......

第 5 步的代码是:

    private static void refreshWidgetAndShowHomeScreen(final Activity activity, int appWidgetId) {
// ... code that does refresh

Intent showHome = new Intent(Intent.ACTION_MAIN);
showHome.addCategory(Intent.CATEGORY_HOME);
showHome.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

activity.setResult(RESULT_OK, showHome);
activity.finish();
activity.startActivity(showHome);
}

该函数是静态的,因为我正在为 android API 7+ 编写小部件,因此它既可以从 Activity 本身调用,也可以从大于 Honeycomb 版本的 Fragment 调用。

4

1 回答 1

1

After a lot of attempts to persuade this to work, I ended up doing the following in onCreate the first time the widget is run, so it is added to the screen immediately. The code closes the activity then immediately restarts it.

Visually, it looks okay. But this sucks because if the user can't authenticate or doesn't want to any more, there will be a dead widget left on their screen. Suggestions welcome...

Workaround:

final Intent intent2 = getIntent();
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK, intent2);
finish();
startActivity(intent2);
于 2013-07-08T12:33:52.110 回答