請耐心等待,因爲我是Android開發新手。Android Widget服務類綁定集合沒有被提供商調用
我正在構建一個小部件,它可以在主屏幕上放置時打開配置活動。當我完成配置並按下「完成」時,小部件提供程序(onUpdate)應該調用小部件服務類,以將可繪製列表綁定到gridview。但是,服務類沒有被調用,並且gridview將變空。對此的任何幫助表示讚賞,代碼如下所示:
*注意:我有一個main.xml,其中包含gridview和另一個具有模板(imageView和textView)gridview單元格的xml。
清單:
<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)}
謝謝!
謝謝你回答Sagi!我按照你說的方式試了一下,不幸的是它對我不起作用......但是你指出了我的正確方向。謝謝! – vanloren1377d
當我經歷這個時,我發現即使在設置結果之後,我的配置活動也沒有調用我的OnReceive()或OnUpdate()方法。我發現這個工作在這裏:[鏈接](http://stackoverflow.com/questions/3818545/how-do-i-force-an-update-in-a-configuration-activity) – vanloren1377d
很高興,它的工作!我個人認爲,在完成活動之後,傾聽WidgetProvider中的onEnabled是更正確的方向 - 據我所知onUpdate是在活動啓動時定期調用的。 –