简体   繁体   中英

Accessing widget from android application

I am trying to add weather widget into my application. I used this code to find target weather widget:

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;
}

}

After that I tried to add AppWidgetHostView into my Activity:

AppWidgetHostView weatherWidget = WT.execute(this).get();
LLWeather.addView(weatherWidget);

It worked but widget showed "Downloading weather data"(internet permissions granted to this activity) and freezed so I cant interact with it. Any ideas how to fix it and access to widget functions?

Do not use get() on your asynctask call as it will not be async anymore. The result of doInBackground will be available in onPostExecute. In onPostExecute you call LLWeather.addView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM