用于绑定未被提供者调用的集合的Android小组件服务类

时间:2012-11-26 20:43:22

标签: android android-widget appwidgetprovider

请耐心等待我,因为我是Android开发的新手。

我正在构建一个小部件,在主屏幕上放置时打开配置活动。当我完成配置并按下“完成”后,小部件提供程序(onUpdate)应该调用小部件服务类以将可绘制列表绑定到gridview。但是,未调用服务类,并且gridview将显示为空。如有任何帮助,请参阅以下代码:

*注意:我有一个main.xml,其中包含gridview,另一个xml具有gridview单元格的模板(imageView和textView)。

清单:

<service android:name=".WidgetService" android:permission="android.permission.BIND_REMOTEVIEWS" android:exported="false" />

<receiver android:name=".WidgetProvider" android:label="@string/app_name">
  <intent-filter>
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  </intent-filter>
  <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
</receiver>

提供者:

public class WidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

 for (int i=0; i < appWidgetIds.length; i++){

   Intent intent = new Intent(context, WidgetService.class);
   intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
   intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));

   RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
   remoteViews.setRemoteAdapter(appWidgetIds[i], R.id.gridview, intent);

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

   super.onUpdate(context, appWidgetManager, appWidgetIds);
 }
......(omitted code)}

服务

public class WidgetService extends RemoteViewsService {

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent){
            return new VZRemoteViewsFactory(this.getApplicationContext(), intent);
        }
    }

    class VZRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory{

       public VZRemoteViewsFactory(Context context, Intent intent){
            thisContext = context;
            appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
       }

       public void onCreate(){
            // code to add drawables to list here
       }

       public RemoteViews getViewAt(int position){
            RemoteViews remoteView = new RemoteViews(thisContext.getPackageName(), R.layout.vzwidget_item);

            //  setting the image view resource this way for now just for testing
            remoteView.setImageViewResource(R.id.launcher_icon, R.drawable.vzicon);
            remoteView.setTextViewText(R.id.textview, "test");

            return remoteView;
       }
.....(omitted code)}

谢谢!

1 个答案:

答案 0 :(得分:0)

根据我的经验(并查看我自己刚刚编写的小部件) - 在启动配置活动时调用OnUpdate,在您从此活动发布结果后,将向appWidgetProvider - android提供以下意图操作。 appwidget.action.APPWIDGET_UPDATE_OPTIONS(在软糖上测试)。

这可能不是处理此问题的最合适方式,但这就是我处理此问题的方法 - 当配置活动发布结果时 - 我启动远程视图服务并开始使用正确的widgetid发送视图。