简体   繁体   中英

Accessing Google Awareness API for Android Crashes App

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;
    }
}
}

I ran into the same problem. I tried restricting the key to the package but still got the 'invalid key' issue.

In the end, this post helped me. Make sure that the meta_data tag is put inside the application tag in the manifest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM