我得到了一个 IntentService,它的工作是从 Google Awareness API 更新天气数据,并将其传递回 Wear 伴侣。
我获得了 API 密钥,获得了位置权限,当从一个简单的 Activity 调用代码时,一切正常。(在我的 mainActivity 中,它是相同的代码,在 IntentService 中,它在同一个包中,在同一个应用程序中)。
代码:
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
mGoogleApiClient = new GoogleApiClient.Builder(this, new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Awareness.SnapshotApi.getWeather(mGoogleApiClient).setResultCallback(new ResultCallback<WeatherResult>() {
@Override
public void onResult(@NonNull WeatherResult weatherResult) {
Log.w("a", "result:" + weatherResult.getStatus().toString());
if (weatherResult.getStatus().isSuccess())
{
Log.w("a", "Weather:" + weatherResult.getWeather().toString());
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
}
}, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}).addApi(Awareness.API).build();
mGoogleApiClient.connect();
所以,这段代码给了我 ok 的状态,并在它在 Activity 中时传递了正确的天气数据。
代码是 ACL_ACCESS_DENIED。位置已启用,已获得权限。
在 GoogleApiClient.Builder 中尝试了“this”、“getApplicationContext”、“getBaseContext”、“getApplication”。他们都没有工作。
有人有解决方案吗?
编辑:这是 IntentService 的相关代码。但它类似于我写的上面的代码:
public class SenderService extends IntentService {
private GoogleApiClient mGoogleApiClient;
private void handleActionWeather() {
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext(), new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.w("a", "wsconn"); handleActionWeatherSupport(mGoogleApiClient);
}
@Override
public void onConnectionSuspended(int i) {
}
}, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.w("a", "wsconnfail:" + connectionResult.toString());
}
}).addApi(Wearable.API).addApi(Awareness.API).useDefaultAccount().build();
mGoogleApiClient.connect();
}
private void handleActionWeatherSupport(final GoogleApiClient mGoogleApiClient) {
if (ActivityCompat.checkSelfPermission(getApplication(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Awareness.SnapshotApi.getWeather(mGoogleApiClient).setResultCallback(new ResultCallback<WeatherResult>() {
@Override
public void onResult(@NonNull WeatherResult wr) {
if (!wr.getStatus().isSuccess()) {
Log.w("a", wr.getStatus().toString());
return;
}
Weather we = wr.getWeather();
Log.w("a", "got:" + we.toString());
}
});
}
...
}