Widget在启动后很难更新

时间:2016-11-14 05:54:37

标签: android widget

我试图为天气应用制作一个小部件,但我遇到了一些问题。当我将它放在家用srceen上但在重启后没有更新/显示数据时它工作正常。我的实施是  1.在onUpdate上,我创建并初始化了天气数据和位置所需的对象

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
    this.context = context;
    this.appWidgetManager = appWidgetManager;

    ForecastApi.create(Global.FORECAST_IO_API_KEY);
    initializeGoogleClient();

    WakeLocker.acquire(context);

    mGoogleApiClient.connect();
}
  1. 在onConnected方法上,我调用了天气数据的请求

    @覆盖 public void onConnected(@Nullable Bundle bundle) {

    SharedPreferences locationSettings =context.getSharedPreferences(Global.SAVED_LOCATION, 0); 
    boolean hasSavedLocation = locationSettings.getBoolean(Global.HAS_SAVED_LOCATION, false);
    List<Address> addresses = null;
    
    if (!hasSavedLocation)
    {
        mLocation = getLastLocation();
        addresses = LocationGetter.getLocationAddress(mLocation, context);
    }
    else
    {
        initializeSavedLocation(addresses);
    }
    
    SharedPreferences settings = context.getSharedPreferences(Global.SETTINGS, 0);
    
    /*
    if (ServicesChecker.isInternetAvailable())
    {
        getWeatherInfo(mLocation, addresses);
    }
    */
    getWeatherInfo(mLocation, addresses);
    

    }

  2. 关于天气响应的成功回调,我更新了小部件

    @覆盖         公共无效成功(WeatherResponse weatherResponse,响应响应)         {

            ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
            int[] allWidgetsIds = appWidgetManager.getAppWidgetIds(thisWidget);
    
            for (int widgetId : allWidgetsIds)
            {
    
                //get weather response
    
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
                views.setImageViewResource(R.id.widget_icon, R.drawable.icon_cloudy);
                views.setTextViewText(R.id.widget_temperature_text, UIUpdater.UpdateCurrentTemperature(weatherResponse.getCurrently(), context));
    
                Intent intent = new Intent(context, MainActivity.class);
    
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    
                views.setOnClickPendingIntent(R.id.layout_holder_widget, pendingIntent);
                //appWidgetManager.updateAppWidget(widgetId, views);
                ComponentName componentName = new ComponentName(context, WidgetProvider.class);
                appWidgetManager.updateAppWidget(componentName, views);
            }
            mGoogleApiClient.disconnect();
            WakeLocker.release();
        }
    
  3. 已经试过让线程睡了几秒钟,以为它无法获得该位置或访问互联网,但没有帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

太傻了。我错过了小部件文档中最重要的部分。 注意:由于AppWidgetProvider是BroadcastReceiver的扩展,因此无法保证您的进程在回调方法返回后继续运行(有关广播生命周期的信息,请参阅BroadcastReceiver)。如果您的App Widget设置过程可能需要几秒钟(可能在执行Web请求时)并且您需要继续进程,请考虑在onUpdate()方法App Widgets| Android Developers中启动服务。将所有逻辑发送到服务后,一切运行顺利。