我正在尝试将天气小部件添加到我的应用程序中。我使用此代码查找目标天气小部件:
public class widgetTask extends AsyncTask<Context, Void, AppWidgetHostView> {
final static int APPWIDGET_HOST_ID = 1;
final static String WEATHER_PACKEGE = "accuweather.android";
final static String WEATHER_CLASS = "accuweather.android.widgets.AL_WidgetProvider";
@Override
protected AppWidgetHostView doInBackground(Context... arg0) {
AppWidgetHostView hostView = null;
AppWidgetManager AWmanager = AppWidgetManager.getInstance(arg0[0]);
AppWidgetHost AWHost = new AppWidgetHost(arg0[0], APPWIDGET_HOST_ID);
AppWidgetProviderInfo AWProviderInfo = new AppWidgetProviderInfo();
int AWId = AWHost.allocateAppWidgetId();
List<AppWidgetProviderInfo> AWProviderInfos = new ArrayList<AppWidgetProviderInfo>();
AWProviderInfos = AWmanager.getInstalledProviders();
for(int j = 0; j < AWProviderInfos.size(); j++)
{
if (AWProviderInfos.get(j).provider.getPackageName().equals("com."+WEATHER_PACKEGE) && AWProviderInfos.get(j).provider.getClassName().equals("com."+WEATHER_CLASS))
{
AWProviderInfo = AWProviderInfos.get(j);
break;
}
}
hostView = AWHost.createView(arg0[0], AWId, AWProviderInfo);
hostView.setAppWidget(AWId, AWProviderInfo);
return hostView;
}
}
之后我尝试将AppWidgetHostView添加到我的Activity中:
AppWidgetHostView weatherWidget = WT.execute(this).get();
LLWeather.addView(weatherWidget);
它工作但是小部件显示&#34;下载天气数据&#34;(授予此活动的互联网权限)并冻结,因此我无法与之交互。 任何想法如何解决它和访问小部件功能?
答案 0 :(得分:0)
不要在asynctask调用上使用get(),因为它不再是异步。 doInBackground的结果将在onPostExecute中可用。在onPostExecute中,您可以调用LLWeather.addView。