从 Activity 更新 Android 小部件

Update Android Widget From Activity(从 Activity 更新 Android 小部件)

本文介绍了从 Activity 更新 Android 小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小部件,它的设置是当我点击它时,它会在活动中打开一些设置.

I have a widget, its setup so that when I click on it, it opens some settings in an activity.

views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);

这会为应用程序配置一些设置.我想要实现的是让小部件更新其视图以在我启动的 Activity 关闭时反映更改的设置.使用更新间隔或任何其他类型的轮询不适合此.

This configures some settings for the application. What I want to achieve is to have the widget update its view to reflect the changed settings when the Activity I launch closes. Using the update interval or any other type of polling isn't appropriate for this.

我在这里和在 android 文档中看到了这个代码使用的几个地方:

I've seen a couple places here and in the android docs this code used:

appWidgetManager.updateAppWidget(mAppWidgetId, views);

但我不知道如何获取 mAppWidgetId 值.我尝试按照此处的小部件配置活动示例 http://developer.android.com/guide/topics/appwidgets/index.html,但是在下面的代码中,

But I don't know how to get the mAppWidgetId value. I tried following the example for a widget configuration activity here http://developer.android.com/guide/topics/appwidgets/index.html, but in the following code,

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

extras 总是为空,所以我从来没有得到 AppWidgetID.

extras is always null, so I never get the AppWidgetID.

好的,现在我只是漫无目的.你觉得我能做什么?

Ok, now I'm just rambling. What do you think I can do?

推荐答案

我终于找到了我想要的答案,它在 updateAppWidget 函数的重载中.

I finally found the answer I was looking for, it was in an overload of the updateAppWidget function.

   appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);

这让我无需知道 appWidgetID 即可访问小部件.我在活动中的最终代码是:

This let me access the widget without having to know the appWidgetID. My final code in my activity is then:

        // Create an Intent to launch ExampleActivity
    Intent intent = new Intent(this, Settings.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);
    finish();

我必须在 Widget 的 onUpdate 方法中进行所有相同的设置工作,但现在每次我退出我的活动时,Widget 都会显示正确的状态.

I have to do all the same setup stuff I had to do in the onUpdate method of the Widget, but now every time I exit my activity the Widget is displaying the correct state.

这篇关于从 Activity 更新 Android 小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 Activity 更新 Android 小部件

基础教程推荐