【问题标题】:How to get weather info with Google Awareness API?如何使用 Google Awareness API 获取天气信息?
【发布时间】:2016-11-14 17:18:44
【问题描述】:

我有一个带有一个按钮的活动,我想用它在同一个活动中为我提供一些天气信息(我在按钮下显示一些 textView...)。我有这样的事情:

 ______________________
| give me weather info |  (button with onClick="addMeteoInfo")
 """"""""""""""""""""""
temperature:                (TextView)
humidity:                     (TextView)

我正在尝试使用 Google Awareness Api 获取有关我当前位置 (https://developers.google.com/awareness/android-api/get-started) 的天气信息,但我遇到了一些麻烦... 我遵循的步骤是:

1) 在我的清单文件中添加:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<meta-data android:name="com.google.android.awareness.API_KEY" android:value="@string/google_maps_key" /> 

<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />

其中“@string/google_maps_key”是我通过 Google Developers Console 获得然后添加到我的 strings.xml 文件资源中的字符串。

2) 添加我的 build.gradle (Module: app) 文件:

compile 'com.google.android.gms:play-services-awareness:9.6.1'

3) 在我的活动中,我有:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nuova_battuta);
    ...
    android.content.Context context;
    GoogleApiClient client = new GoogleApiClient.Builder(context)
        .addApi(Awareness.API)
        .build();
    client.connect(); 
}

// onClick method for button "give me weather info"
public void addMeteoInfo(View view){
    richiediInfoMeteo();
}

public void richiediInfoMeteo() {
    if( !checkLocationPermission() ) {
        return;
    }

    Awareness.SnapshotApi.getWeather(mGoogleApiClient)
            .setResultCallback(new ResultCallback<WeatherResult>() {
                @Override
                public void onResult(@NonNull WeatherResult weatherResult) {

                    if (!weatherResult.getStatus().isSuccess()) {      <----HERE
                        Log.e(TAG, "Could not get weather.");

                        return;
                    }

                    Weather weather = weatherResult.getWeather();
                    Log.e("Tuts+", "Temp: " + weather.getTemperature(Weather.FAHRENHEIT));
                    Log.e("Tuts+", "Feels like: " + weather.getFeelsLikeTemperature(Weather.FAHRENHEIT));
                    Log.e("Tuts+", "Dew point: " + weather.getDewPoint(Weather.FAHRENHEIT));
                    Log.e("Tuts+", "Humidity: " + weather.getHumidity() );

                    //converto i valori interi ottenuti dall'API Google play services, in stringhe
                    String temperaturaStr = Double.toString(weather.getTemperature(Weather.CELSIUS));
                    String temperaturaPercepitaStr = Double.toString(weather.getFeelsLikeTemperature(Weather.CELSIUS));
                    String puntoRugiadaStr = Double.toString(weather.getDewPoint(Weather.CELSIUS));
                    String umiditaStr = Double.toString(weather.getHumidity());

                    //prelevo id visualizzatori di tali valori nel layout
                    mostraTemperatura = (TextView) findViewById(R.id.temperatura);
                    mostraTemperaturaPercepita = (TextView) findViewById(R.id.temperaturaPercepita);
                    mostraPuntoRugiada = (TextView) findViewById(R.id.puntoDiRugiada);
                    mostraUmidita = (TextView) findViewById(R.id.umidita);

                    // setto i visualizzatori ai valori convertiti in stringhe
                    mostraTemperatura.setText(temperaturaStr);
                    mostraTemperaturaPercepita.setText(temperaturaPercepitaStr);
                    mostraPuntoRugiada.setText(puntoRugiadaStr);
                    mostraUmidita.setText(umiditaStr);

                }
            });
}


private boolean checkLocationPermission() {
    //se permessi non disponibili allora li richiedo tramite finestra dialog
    if( !hasLocationPermission() ) {
        Log.e("Tuts+", "Does not have location permission granted");
        requestLocationPermission();
        return false;
    }
    //altrimenti se possiede già permessi
    return true;
}

private boolean hasLocationPermission() {
    return ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION )
            == PackageManager.PERMISSION_GRANTED;
}

private void requestLocationPermission() {
    ActivityCompat.requestPermissions(
            NuovaBattutaActivity.this,
            new String[]{ Manifest.permission.ACCESS_FINE_LOCATION },
            RICHIESTA_PERMESSO_INFO_METEO );
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case RICHIESTA_PERMESSO_INFO_METEO:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //granted
                richiediInfoMeteo();
            } else {
                Log.e("Tuts+", "Location permission denied.");
            }
        default:
            break;
    }
}

因此,当我在 AVD 中运行我的应用程序时,我总是在控制台中获得以下消息: 无法获得天气。即方法weatherResult.getStatus().isSuccess()(在richiediInfoMeteo() 方法中)总是返回false。 我哪里错了?我该如何处理?

提前致谢。

【问题讨论】:

    标签: android android-studio google-play-services weather-api google-awareness


    【解决方案1】:

    尝试使用weatherResult.getStatus().getStatusCode() 函数。这会返回一个可能的错误代码,可以是looked up here

    一个可能的问题是您的设备上未启用定位服务。启用这些并重试,这可能会解决您的问题。我遇到了类似的问题(错误代码为 7503)。

    【讨论】:

      【解决方案2】:

      对于从 Awareness API 获取天气信息时遇到问题的任何人,这里有一个使用 API 版本 15.0.1 的示例:

      // in gradle.build
       dependencies {
           ...
           implementation 'com.google.android.gms:play-services-awareness:15.0.1'
       }
      
      
      // in class GetWeatherInfoJobService
      public class GetWeatherInfoJobService extends JobService {
      
          private static final String TAG = "GetWeatherJobService";
      
          public GetWeatherInfoJobService() {
          }
      
          @SuppressLint("MissingPermission")
          @Override
          public boolean onStartJob(JobParameters params) {
      
              Log.i(TAG, "Job started");
      
              Awareness.getSnapshotClient(this).getWeather()
                          .addOnCompleteListener((t) -> {
                              if (t.isSuccessful()){
      
                                  Log.i(TAG, "Temperature in Celsius: " +     t.getResult().getWeather().getTemperature(Weather.CELSIUS));
                                  jobFinished(params, false);
                              }
                          })
                          .addOnFailureListener(e -> {
      
                              Log.e(TAG, "Weather task failed");
                              e.printStackTrace();
      
                          });
      
              return true;
          }
      
          @Override
          public boolean onStopJob(JobParameters params) {
              Log.e(TAG, "Job stopped" );
              return false;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2013-01-15
        • 2012-03-29
        • 1970-01-01
        • 2012-02-24
        • 1970-01-01
        • 2021-12-15
        • 2012-10-08
        • 2015-02-04
        • 1970-01-01
        相关资源
        最近更新 更多