Android 自定义Launcher添加自定义widget,无法更新widget界面

浏览:22日期:2022-11-01

问题描述

Android 自定义Launcher添加自定义widget,无法更新widget界面,自定义widget在系统launcher上可以更新,系统的widget比如时钟,在自定义launcher上可以更新。

AppWidgetProvider代码如下:

@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {super.onUpdate(context, appWidgetManager, appWidgetIds);SimpleDateFormat dateFormat = new SimpleDateFormat('HH:mm:ss');String dateStr = dateFormat.format(new Date());RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);views.setTextViewText(R.id.tv_update, dateStr);Log.i('TAG','--'+dateStr);appWidgetManager.updateAppWidget(new ComponentName(context, WidgetProvider.class),views); }

自定义launcher相关的代码如下onCreate里面创建了 ,

//得到com.test包名的所有widegt,并且分配一个appwidgetId,保存起来mAppWidgetHost = new AppWidgetHost(MainActivity.this, HOST_ID);mAppWidgetHost.startListening();mAppWidgetManager = AppWidgetManager.getInstance(MainActivity.this);List<AppWidgetProviderInfo> providers = mAppWidgetManager.getInstalledProviders();for (int i = 0; i < providers.size(); i++) { ComponentName provider = providers.get(i).provider; if (provider.getPackageName().contains('com.test')) {surfAppWidgetList.add(providers.get(i));surfAppWidgetIdList.add(mAppWidgetHost.allocateAppWidgetId());LogUtil.printlf('-->' + provider.getPackageName()); }}//intent里面可以传入mAppWidgetIds=new int[surfAppWidgetIdList.size()];

然后循环添加到父布局里面去

AppWidgetHostView hostView = mAppWidgetHost.createView(this, surfAppWidgetIdList.get(i), surfAppWidgetList.get(i)); addView(hostView);

大概什么问题?

问题解答

回答1:

已经解决。需要进行bindAppWidgetId();而bindAppWidgetId需要系统权限。必须将自身应用提升至系统应用。

相关文章: