我正在嘗試爲天氣應用製作小部件,但我正面臨着一些問題。它可以正常工作,當我把它放在家庭srceen但重新啓動後不更新/顯示數據。我的實現是 1.On所述的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();
}
在onConnected方法我呼籲請求氣象數據
@Override 公共無效onConnected(@Nullable束束) {
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);
}
天氣響應的成功回調我更新已試圖把小部件
@覆蓋 公共無效成功(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(); }
線程睡覺幾秒鐘,認爲它無法獲得位置或訪問互聯網,但沒有幫助。提前致謝。