2016-11-14 70 views
0

我正在嘗試爲天氣應用製作小部件,但我正面臨着一些問題。它可以正常工作,當我把它放在家庭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(); 
        } 
    
  • 線程睡覺幾秒鐘,認爲它無法獲得位置或訪問互聯網,但沒有幫助。提前致謝。

    回答

    0

    太傻了。我錯過了Widget文檔中最重要的部分。 注意:由於AppWidgetProvider是BroadcastReceiver的擴展,因此在回調方法返回後您的進程不保證保持運行(有關廣播生命週期的信息,請參閱BroadcastReceiver)。如果您的App Widget安裝過程可能需要幾秒鐘(可能在執行Web請求時),並且您需要繼續進行,請考慮在onUpdate()方法App Widgets| Android Developers中啓動服務。將所有邏輯發送到服務之後,所有操作都可以順利進行

    相關問題