当通过代码重新添加窗口小部件不回应(Widgets don't respond when r

2019-06-17 10:55发布

我工作的启动。 它让我们的用户在列表中添加窗口小部件,它工作正常。 我存储有关部件信息(包名,类名和它在屏幕上的坐标),当用户添加一个屏幕在我的数据库。

当应用程序被重新启动(或设备本身)予添加这些(用户选择的)通过代码部件回:

// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();

// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();

// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();

for(int j = 0; j < appWidgetInfos.size(); j++)
{
    if (appWidgetInfos.get(j).provider.getPackageName().equals(PackageName) && appWidgetInfos.get(j).provider.getClassName().equals(ClassName))
    {
        // Get the full info of the required widget
        newAppWidgetProviderInfo = appWidgetInfos.get(j);
        break;
    }
 }

// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

// Add it to your layout
RelativeLayout widgetLayout = (RelativeLayout) findViewById(R.id.widgetLayout);
widgetLayout.addView(hostView);

小部件已成功添加到布局,但现在看来似乎尚未启用/更新。 它不响应点击(例如,模拟时钟),并没有显示任何数据(例如,音乐播放插件),虽然我已经把这个:

@Override
protected void onStart() {
    super.onStart();
    appWidgetHost.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    appWidgetHost.stopListening();
}

因为很长一段时间我坚持就可以了。 搜索了很多,但似乎我是唯一一个在这个世界上解决这个问题。

Answer 1:

我们可以调用一个对话框,要求用户允许我们的应用程序能够绑定控件的ID用下面的代码:

Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, sSavedWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, mWidgetInfo.provider);
startActivityForResult(intent, REQUEST_BIND_WIDGET);

和绑定控件的ID,使他们真正一起工作:

Bundle opts = new Bundle();
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, minHeight);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, maxHeight);

widgetManager.bindAppWidgetIdIfAllowed(widgetId, mWidgetInfo, opts);

欲了解更多信息,请参阅:

  • AppWidgetManager.ACTION_APPWIDGET_BIND
  • AppWidgetManager.bindAppWidgetIdIfAllowed()

我希望有人能有相同的5年前的回答。



文章来源: Widgets don't respond when re-added through code