0

我需要一种方法来确定配置活动中当前小部件的哪个 AppWidgetProvider 处于活动状态。我当前的解决方案在某些设备上导致 NullException,appWidgetInfo.provider 不知何故为空。

是否有更好的方法来确定哪个 AppWidgetProvider 对应于特定的 appWidgetId。

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
AppWidgetProviderInfo appWidgetInfo = appWidgetManager.getAppWidgetInfo(widgetId);

Intent intent = new Intent();
intent.putExtra(
    AppWidgetManager.EXTRA_APPWIDGET_ID, 
             widgetId);
intent.setAction(RemoteWidgetViewsFactory.KEY_WIDGET_SETTING_REFRESH);

String appWidgetProviderName = appWidgetInfo.provider.getClassName();
if(appWidgetProviderName.equals(WidgetProvider.class.getName())) {
    intent.setClass(context, WidgetProvider.class);
}
else if(appWidgetProviderName.equals(WidgetProviderLarge.class.getName())) {
    intent.setClass(context, WidgetProviderLarge.class);
}

sendBroadcast(intent);
4

1 回答 1

1

我实际上遇到了同样的问题,因为我还需要确定实际的 AppWidgetProvider 类。你的问题确实帮助了我,我可能可以帮助你。只需实现这样的方法,您就不必为每个 AppProvider 类编写代码:

    private static Class<?> getAppWidgetProviderClass(Context context, int appWidgetId){
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    AppWidgetProviderInfo appWidgetInfo = appWidgetManager.getAppWidgetInfo(appWidgetId);
    String appWidgetProviderName = appWidgetInfo.provider.getClassName();
    Class<?> myProvider = null;
    try {
        myProvider = Class.forName(appWidgetProviderName);
    } catch (ClassNotFoundException cnf){
        Log.e("myProviderClass","Class:" + appWidgetProviderName + " not found!");
    }
    return myProvider;
}

将其用于类定义意图之后:

Intent myIntent = new Intent(context, getAppWidgetProviderClass(context, appWidgetId));

希望对你有帮助!

于 2012-12-19T17:13:59.997 回答