小部件配置更改后不刷新 [英] widget doesn't refresh after configuration changes

查看:148
本文介绍了小部件配置更改后不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了我的应用程序的AppWidget,你可以选择你喜欢的一个地方的名称,它表明你从那个地方照片。

它有一个配置Activity(我用的是应用程序本身的相同配置活动)
第一次加时,小部件和它的配置HANDELING工作正常:我选择我喜欢的地方,我看到了知情同意;

问题是每当我重新启动设备(或它超出休眠模式)
然后当我点击它(小部件)我进入配置活动 - 更改到所需的图片并没有任何反应
当我调试,我可以看到:

  appWidgetManager.updateAppWidget(mAppWidgetId,意见);
mAppWidgetId =

有一个 ID 的意见不是
还等什么黑客是怎么回事?
我的想法是,在设备的重启为widgetid变化,我不喜欢我应该处理它。
顺便说一句,如果尝试在模拟器上同我没有问题,一切工作正常。

这是我的code:

的Manifest.xml:

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.test.dryrun安卓版code =3
    机器人:=的versionName1.1安卓的installLocation =自动>
    <采用-SDK安卓的minSdkVersion =8/>    <应用机器人:图标=@绘制/ ic_launcher_test
        机器人:标签=@字符串/ APP_NAME机器人:主题=@安卓风格/ Theme.NoTitleBar.Fullscreen
        机器人:可调试=真正的>< - 不同<机器人:主题=@风格/ Theme.NoBackground - >        <! - 主要活动 - >
        <活动机器人:MyActivityNAME =>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>
                <类机器人:名字=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;        <! - preferences - >        <活动机器人:preferences.Edit preferencesNAME =>
             <作用机器人:名字=android.appwidget.action.APPWIDGET_CONFIGURE/>
        < /活性GT;        <! - 部件 - >        <! - 小工具 - >
        <接收机器人:Widget.testWidgetNAME =机器人:标签=@字符串/ app_widget _>
            &所述;意图滤光器>
                <作用机器人:名字=android.appwidget.action.APPWIDGET_UPDATE/>
                &所述;! - 动作
                    机器人:名字=。com.test.dryrun.Widget.testWidget preFENCES_WIDGET_CONFIGURE/ - >
            &所述; /意图滤光器>
            <元数据机器人:名字=android.appwidget.provider
                机器人:资源=@ XML / test_widget__provider/>
        < /接收器>
        <服务机器人。Widget.testWidget $ WidgetServiceNAME = />        <使用许可权的android:NAME =android.permission.BIND_REMOTEVIEWS>< /使用许可权>
    < /用途>
< /清单>

appwidget_provider XML

 < appwidget提供商的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
 安卓了minWidth =146dip
 安卓了minHeight =146dip
 机器人:updatePeriodMillis =0
 机器人:initialLayout =@布局/ test_widget
/>

Widget类

 公共类testWidget扩展AppWidgetProvider {
    公共静态字符串preFENCES_WIDGET_CONFIGURE =ActionConfigureWidget;    @覆盖
    公共无效的onUpdate(上下文的背景下,AppWidgetManager appWidgetManager,INT [] appWidgetIds){
        意图svcIntent =新意图(背景下,WidgetService.class);
        小部件= appWidgetIds;
        context.startService(svcIntent);
    }
  @覆盖
  公共无效的onReceive(上下文的背景下,意图意图)
  {        // V1.5修复不调用onDelete行动
        最后弦乐行动= intent.getAction();
        如果(AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(动作))
        {
            最终诠释appWidgetId = intent.getExtras()调用getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            如果(appWidgetId!= AppWidgetManager.INVALID_APPWIDGET_ID)
            {
                this.onDeleted(背景下,新的INT [] {appWidgetId});
            }
        }
        其他
        {
            super.onReceive(背景下,意图);
        }
    }    //公共无效updateWidget()
    / **
    * @参数方面
    * @参数remoteViews
    * /
    公共静态无效updateWidget(上下文的背景下,RemoteViews remoteViews)
    {
        字符串preFIX = context.getString(R.string ._ preFIX);        共享preferences preFS = preferenceManager.getDefaultShared preferences(背景);
        字符串ToShow = prefs.getString(context.getString(
                     R.string.Widget_string)
                     context.getString(R.string.default_string));        字符串PKGNAME = context.getPackageName();
        INT渣油= context.getResources()则getIdentifier(preFIX + ToShow,绘制,PKGNAME)。        WidgetController widgetController = WidgetController.getInstance();
        widgetController.setRemoteViewImageViewSource(remoteViews,R.id.WidgetImage,渣油);
    }    公共静态类WidgetService延伸服务
    {
        @覆盖
        公共无效调用onStart(意向意图,诠释startId)
        {
            super.onStart(意向,startId);
            //更新窗口小部件
            RemoteViews远程视窗= buildRemoteView(本);            //推送更新主屏幕
            WidgetController.getInstance()。pushUpdate(
                    远程视窗,
                    getApplicationContext(),
                    testWidget.class);            //没有更多的更新,因此停止服务和免费资源
            stopSelf();
        }        公共RemoteViews buildRemoteView(上下文的背景下)
        {
            RemoteViews remoteViews =新的RemoteViews(context.getPackageName(),R.layout.test_widget);            意图configIntent =新意图(背景下,编辑preferences.class);
            configIntent.setAction(testWidget preFENCES_WIDGET_CONFIGURE);
            configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,窗口小部件[0]);            //configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            的PendingIntent runtestPendingIntent = PendingIntent.getActivity(上下文,0,configIntent,PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.WidgetImage,runtestPendingIntent);            WidgetController控制器= WidgetController.getInstance();            controller.updateWidget(背景下,remoteViews);            返回remoteViews;
        }        @覆盖
        公共无效onConfigurationChanged(配置NEWCONFIG)
        {
            INT oldOrientation = this.getResources()getConfiguration()方向。;            如果(newConfig.orientation!= oldOrientation)
            {
                //更新窗口小部件
                RemoteViews远程视窗= buildRemoteView(本);                //推送更新主屏幕
                WidgetController.getInstance()。pushUpdate(
                        远程视窗,
                        getApplicationContext(),
                        testWidget.class);
            }
        }        @覆盖
        公众的IBinder onBind(意向为arg0)
        {
            // TODO自动生成方法存根
            返回null;
        }
    }
}

prefences类

 公共类编辑preferences扩展preferenceActivity实现OnShared preferenceChangeListener
{
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        加preferencesFromResource(R.xml preferences);
        意向意图= getIntent();
        m_extras = intent.getExtras();
    }
    私人捆绑m_extras;    @覆盖
    公共无效onShared preferenceChanged(共享preferences共享preferences,串键)
    {
        如果(key.equals(的getString(R.string.rlvntString)))
        {
            上下文CTX = getApplicationContext();
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(CTX);
            的setResult(RESULT_CANCELED);
            如果(m_extras!= NULL)
            {
                意图resultValue =新的Intent();                字符串的StringID = AppWidgetManager.EXTRA_APPWIDGET_ID;
                mAppWidgetId = m_extras.getInt(
                            的StringID,
                            AppWidgetManager.INVALID_APPWIDGET_ID);
                RemoteViews意见=新的RemoteViews(ctx.getPackageName(),R.layout.test_widget);                。WidgetController.getInstance()updateWidget(CTX,意见);                appWidgetManager.updateAppWidget(mAppWidgetId,意见);
                resultValue.putExtra(的StringID,mAppWidgetId);
                的setResult(RESULT_OK,resultValue);
                完();
            }
        }
    }
}


解决方案

buildRemoteView必须编辑preferences定义不小部件类。我有同样的问题,但研究这个后:的http://开发商。 android.com/guide/topics/appwidgets/index.html#Configuring~~V 我感动了所有远程视窗建筑物配置的活动 - 它的工作现在

I wrote an AppWidget for my app that you can choose a name of place you like and it shows you a pic from that place.

It has a configuration Activity (I used the same configuration activity of the app itself) when first added, the widget and the it's configuration handeling works fine: I choose a place I like and I see the pic;

Problem is Whenever I restart the device(or it goes out of sleep mode) then when I click on it(the widget) I go into the configuration activity - change to the desired pic and nothing happens when I debug I can see that:

appWidgetManager.updateAppWidget(mAppWidgetId, views);
mAppWidgetId = 

has an id, and views is not null. so what the hack is going on? my idea is that on restart of the device the widgetId changes, and that I don't handle it like I should. BTW if try the same on the emulator I have no problems everything works fine

here is my code:

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.dryrun" android:versionCode="3"
    android:versionName="1.1" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/ic_launcher_test"
        android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:debuggable="true"><!-- different< android:theme="@style/Theme.NoBackground" -->

        <!-- Main Activity -->
        <activity android:name=".MyActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Preferences -->

        <activity android:name=".Preferences.EditPreferences">
             <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
        </activity>

        <!-- Widgets -->

        <!--  Widget-->
        <receiver android:name=".Widget.testWidget" android:label="@string/app_widget_">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <!--action
                    android:name="com.test.dryrun.Widget.testWidget.PREFENCES_WIDGET_CONFIGURE" /-->
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/test_widget__provider" />
        </receiver>
        <service android:name=".Widget.testWidget$WidgetService" />

        <uses-permission android:name="android.permission.BIND_REMOTEVIEWS"></uses-permission>
    </application>
</manifest>

appwidget_provider xml

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
 android:minWidth="146dip"
 android:minHeight="146dip"
 android:updatePeriodMillis="0"
 android:initialLayout="@layout/test_widget"
/>

Widget Class

public class testWidget extends AppWidgetProvider {
    public static String PREFENCES_WIDGET_CONFIGURE = "ActionConfigureWidget";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Intent svcIntent = new Intent(context, WidgetService.class);
        widgets = appWidgetIds;
        context.startService(svcIntent);
    }


  @Override
  public void onReceive(Context context, Intent intent) 
  {

        // v1.5 fix that doesn't call onDelete Action
        final String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action))
        {
            final int appWidgetId = intent.getExtras().getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID)
            {
                this.onDeleted(context, new int[] { appWidgetId });
            }
        }
        else
        {
            super.onReceive(context, intent);           
        }
    }

    //public void updateWidget()
    /**
    * @param context
    * @param remoteViews
    */
    public static void updateWidget(Context context, RemoteViews remoteViews)
    {
        String Prefix = context.getString(R.string._prefix);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String ToShow = prefs.getString(context.getString(
                     R.string.Widget_string),
                     context.getString(R.string.default_string));

        String pkgName = context.getPackageName();
        int resID = context.getResources().getIdentifier(Prefix + ToShow, "drawable", pkgName);

        WidgetController widgetController = WidgetController.getInstance();
        widgetController.setRemoteViewImageViewSource(remoteViews, R.id.WidgetImage, resID);
    }

    public static class WidgetService extends Service
    {
        @Override
        public void onStart(Intent intent, int startId)
        {
            super.onStart(intent, startId);
            // Update the widget
            RemoteViews remoteView = buildRemoteView(this);

            // Push update to homescreen
            WidgetController.getInstance().pushUpdate(
                    remoteView, 
                    getApplicationContext(),
                    testWidget.class);

            // No more updates so stop the service and free resources
            stopSelf();
        }

        public RemoteViews buildRemoteView(Context context)
        {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.test_widget);

            Intent configIntent = new Intent(context, EditPreferences.class);
            configIntent.setAction(testWidget.PREFENCES_WIDGET_CONFIGURE);


            configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgets[0]);

            //configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent runtestPendingIntent = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.WidgetImage, runtestPendingIntent);

            WidgetController controller =  WidgetController.getInstance();

            controller.updateWidget(context, remoteViews);

            return remoteViews;
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig)
        {
            int oldOrientation = this.getResources().getConfiguration().orientation;

            if(newConfig.orientation != oldOrientation)
            {
                // Update the widget
                RemoteViews remoteView = buildRemoteView(this);

                // Push update to homescreen
                WidgetController.getInstance().pushUpdate(
                        remoteView, 
                        getApplicationContext(),
                        testWidget.class);
            }
        }

        @Override
        public IBinder onBind(Intent arg0)
        {
            // TODO Auto-generated method stub
            return null;
        }
    }
}

Prefences class

public class EditPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        Intent intent = getIntent();
        m_extras = intent.getExtras();
    }
    private Bundle m_extras;

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) 
    {
        if(key.equals(getString(R.string.rlvntString)))
        {
            Context ctx = getApplicationContext();
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(ctx);
            setResult(RESULT_CANCELED);
            if (m_extras != null) 
            {
                Intent resultValue = new Intent();

                String stringID = AppWidgetManager.EXTRA_APPWIDGET_ID;
                mAppWidgetId = m_extras.getInt(
                            stringID, 
                            AppWidgetManager.INVALID_APPWIDGET_ID);
                RemoteViews views = new RemoteViews(ctx.getPackageName(),R.layout.test_widget);

                WidgetController.getInstance().updateWidget(ctx, views);

                appWidgetManager.updateAppWidget(mAppWidgetId, views);
                resultValue.putExtra(stringID, mAppWidgetId);
                setResult(RESULT_OK, resultValue);
                finish();
            }
        }
    }
}

解决方案

buildRemoteView must be defined in EditPreferences not in Widget Class. I had the same problem, but after studying this: http://developer.android.com/guide/topics/appwidgets/index.html#Configuring I moved all remoteView buildings to config activity - it's working now

这篇关于小部件配置更改后不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆