我正在尝试使用Android Awareness来访问天气数据。我的应用程序在显示数据之前崩溃了。我认为问题出在onComplete方法内部,因为在崩溃之前,UI确实会在屏幕上短暂闪烁,并且我能够运行调试器直到之前的代码行。
控制台显示"FATAL EXCEPTION: GoogleApiHandler“和"java.lang.SecurityException:包的API Key无效”我使用了一个不受限制的API key,以确保问题不是指纹或包名。我已经在清单中包含了我的API密钥,使用
<meta-data android:name="com.google.android.awareness.API_KEY" android:value="[key here]"/>
我的应用程序模块Gradle脚本还包括“依赖项中的实现'com.google.android.gms:play-services-awareness:11.6.0'”“。
还有一个警告说Awareness.API已被弃用,但我不知道用什么来代替它,因为文档中使用了它。
我的代码如下。
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;
}
}
}发布于 2017-12-02 13:35:02
我遇到了同样的问题。我尝试将密钥限制在包中,但仍然出现“无效密钥”的问题。
最后,这个post帮助了我。确保将meta_data标记放在清单中的application标记内。
https://stackoverflow.com/questions/47461573
复制相似问题