2017-07-29 3 views
0

私は天気予報のアプリケーションに取り組んできましたが、それは完璧ではないことを知っています(私はAndroidの開発を始めたばかりです)。しかし、起動時に気象情報を更新する方法がわかりません。私はonCreate()メソッドですべてを保持しようとしましたが、最初に起動したときに使用した場所と条件に "スティック"します。onCreate()で天気を更新するには?

私は、これを押すと新しい位置と気象条件を取得するボタンでこれを回避することができましたが、これはあまり直感的ではありません。私はアプリの起動時に新しい条件をどうやって得ることができるのだろうかと思っています。それはonRestart()を呼び出す必要がありますか?ここで

は、アプリで私の唯一のアクティビティです:

package com.photonfighterlabs.dropweather; 

import android.Manifest; 
import android.app.Activity; 
import android.content.pm.PackageManager; 
import android.graphics.drawable.Drawable; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.os.Bundle; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.util.Log; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.ftoslab.openweatherretrieverz.CurrentWeatherInfo; 
import com.ftoslab.openweatherretrieverz.OpenWeatherRetrieverZ; 
import com.ftoslab.openweatherretrieverz.WeatherCallback; 
import com.ftoslab.openweatherretrieverz.WeatherUnitConverter; 
import com.google.android.gms.location.FusedLocationProviderClient; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.tasks.OnSuccessListener; 

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 


public class WeatherActivity extends Activity { 

    private double lat; 
    private double lng; 

    private String temp; 
    private String icon; 

    private TextView tempTextView; 
    private TextView cityTextView; 
    private TextView conditionsTextView; 

    private int LOCATION_PERMISSION_ID = 1001; 

    CurrentWeatherInfo currentWeatherInfoF; 

    private String city; 
    private List<Address> addresses; 

    private FusedLocationProviderClient mFusedLocationClient; 

    OpenWeatherRetrieverZ retriever; 

    ImageView image; 

    Geocoder geocoder; 

    @Override 
    public void onCreate(Bundle bundle) { 
     super.onCreate(bundle); 
     setContentView(R.layout.activity_weather); 

     retriever = new OpenWeatherRetrieverZ(API_KEY); // hidden for obvious reasons, but working 


     mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 
     geocoder = new Geocoder(this, Locale.getDefault()); 

     tempTextView = (TextView) findViewById(R.id.temp_text_view); 
     cityTextView = (TextView) findViewById(R.id.city_text_view); 
     conditionsTextView = (TextView) findViewById(R.id.conditions_text_view); 

     image = (ImageView) findViewById(R.id.conditions_image); 






     if (ContextCompat.checkSelfPermission(WeatherActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_ID); 
      return; 
     } 

     mFusedLocationClient.getLastLocation() 
       .addOnSuccessListener(this, new OnSuccessListener<Location>() { 
        @Override 
        public void onSuccess(Location location) { 
         if (location != null) 
          lat = location.getLatitude(); 
         lng = location.getLongitude(); 

         try { 
          addresses = geocoder.getFromLocation(lat, lng, 1); 

         } catch (IOException e) { 
          e.printStackTrace(); 
         } 

         if (!addresses.isEmpty()) { 
          city = addresses.get(0).getLocality(); 
          cityTextView.setText("Current Weather - " + city); 
          Log.d("City", city); 
         } 

         Log.d("LAT", String.valueOf(lat)); 
         Log.d("LNG", String.valueOf(lng)); 
        } 
       }); 

     retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() { 
      @Override 
      public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) { 
       currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo); 

      } 

      @Override 
      public void onFailure(String error) { 
       Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show(); 
      } 
     }); 

    } 

    public void onRetrieveButtonClick(View view) { 

     mFusedLocationClient.getLastLocation() 
       .addOnSuccessListener(this, new OnSuccessListener<Location>() { 
        @Override 
        public void onSuccess(Location location) { 
         if (location != null) 
          lat = location.getLatitude(); 
         lng = location.getLongitude(); 

         try { 
          addresses = geocoder.getFromLocation(lat, lng, 1); 

         } catch (IOException e) { 
          e.printStackTrace(); 
         } 

         if (!addresses.isEmpty()) { 
          city = addresses.get(0).getLocality(); 
          cityTextView.setText("Current Weather - " + city); 
          Log.d("City", city); 
         } 

         Log.d("LAT", String.valueOf(lat)); 
         Log.d("LNG", String.valueOf(lng)); 
        } 
       }); 


     retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() { 
      @Override 
      public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) { 
       currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo); 

      } 

      @Override 
      public void onFailure(String error) { 
       Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     temp = currentWeatherInfoF.getCurrentTemperature(); 

     Log.d("TMP : ", String.valueOf(temp)); 

     tempTextView.setText(String.valueOf((int) Double.parseDouble(temp)) + (char) 0x00B0); 
     conditionsTextView.setText(currentWeatherInfoF.getWeatherDescriptionLong()); 


     String iconURL = currentWeatherInfoF.getWeatherIconLink().toString(); 

     Pattern p = Pattern.compile("\\d\\w(n|d)"); 
     Matcher m = p.matcher(iconURL); 


     if (m.find()) { 
      icon = m.group(); 
      Log.d("ICON", icon); 
      String iconName = "r" + icon; 
      image.setImageResource(getResources().getIdentifier(iconName, "drawable", getPackageName())); 
      Log.d("NAME", iconName); 
     } 

    } 




} 
+0

10秒ごとに再開メソッドを呼び出す –

+0

ロケーション選択のseprateアクティビティを作成します。 – Anil

+0

oncreateでデータを更新するサービスを作成します。 –

答えて

1

getLastLocation()updateCurrentWeatherInfo(...)は両方とも非同期操作です。両方を同時に開始すると、ポジションが利用可能になる前にupdateCurrentWeatherInfoが実行される可能性が高くなります。

たとえば、onSuccessリスナーのように、ポジションを取得した後で開始する必要があります。

0

あなたはonResume()メソッドを試しましたか?

あなたはそれを使用することができますし、ビューが見えるのWiとき

0

Awarenessは場所へのアクセスを管理したり、サーバから天候を照会するAPIと統合することなく、デバイスの場所でgetWeather() APIメソッドを介して天気予報を取得するためのsnapshot-APIを提供していますオンデマンド。

具体的なコード・スニペット:

Awareness.SnapshotApi.getWeather(mGoogleApiClient) 
    .setResultCallback(new ResultCallback<WeatherResult>() { 
    @Override 
    public void onResult(@NonNull WeatherResult weatherResult) { 
     if (!weatherResult.getStatus().isSuccess()) { 
     Log.e(TAG, "Could not get weather."); 
     return; 
     } 
     Weather weather = weatherResult.getWeather(); 
     Log.i(TAG, "Weather: " + weather); 
    } 
    }); 

インスタンスAPIによって返される天気クラスの説明についてはhereを参照してください。

これを使用する利点は、コードを大量に簡素化し、ロケーションリクエストを管理しなくても、必要なだけ頻繁にAPIを呼び出す必要がなくなることです(電池の消耗が多すぎるネットワーク要求を避けるためにキャッシュがあると思います) 。