I am attempting to use the Android Awareness API to access weather data. My app crashes before showing the data. I believe the problem is inside the onComplete method because the UI does briefly flash on the screen before crashing and I am able to run the debugger up to the line before.
The console says "FATAL EXCEPTION: GoogleApiHandler" and "java.lang.SecurityException: Invalid API Key for package" I am using an unrestricted API key to ensure the problem is not the fingerprint or package name. I have included my API key in the manifest using
<meta-data
android:name="com.google.android.awareness.API_KEY"
android:value="[key here]"/>
My app module Gradle script also includes "implementation 'com.google.android.gms:play-services-awareness:11.6.0'" in the dependencies.
There is also a warning that Awareness.API is deprecated but I don't know what to replace that with because it is used in the documentation.
My code is below.
public class MainActivity extends AppCompatActivity {
private static int MY_PERMISSION_LOCATION;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
GoogleApiClient client = new GoogleApiClient.Builder(this.getApplicationContext())
.addApi(Awareness.API)
.build();
client.connect();
SnapshotClient sc = Awareness.getSnapshotClient(this);
Task<WeatherResponse> weatherResponseTask = sc.getWeather().addOnCompleteListener(new OnCompleteListener<WeatherResponse>() {
@Override
public void onComplete(@NonNull Task<WeatherResponse> task) {
WeatherResponse wr = task.getResult();
Weather weather = wr.getWeather();
float temp = weather.getTemperature(Weather.FAHRENHEIT);
TextView textView = findViewById(R.id.tempText);
textView.setText("It is currently " + temp + " degrees outside.");
}
});
} else {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_LOCATION
);
return;
}
}
}