简体   繁体   English

从Android应用程序访问小部件

[英]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添加到我的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. 不要在您的asynctask调用上使用get(),因为它将不再是异步的。 The result of doInBackground will be available in onPostExecute. doInBackground的结果将在onPostExecute中可用。 In onPostExecute you call LLWeather.addView. 在onPostExecute中,您调用LLWeather.addView。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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