启动我的Google Play服务客户端,如下所示:
public class MyApplication extends Application implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
protected synchronized GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/* GoogleApiClient.ConnectionCallbacks */
@Override
public void onConnected(Bundle bundle) {
Log.v(TAG, "Google play services connected.");
boolean isConnected = mGoogleApiClient.isConnected(); // - this is true
boolean isLocAvailable = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient).isLocationAvailable();
// this causes NullPointerException because getLocationAvailabality() returns null. WHY ????
.
.
.
}
}
Google Play服务库版本为Rev.24。 为什么会出现这个空指针eception? Google API客户端已初始化,已连接,每个文档应该是什么样的?存在WiFi连接...
答案 0 :(得分:1)
你还有这个问题吗?它在我的应用程序(在Moto X 2013上测试)与Google Play Service Libary Rev 25一起运行良好
但是当我在已经安装了Google Apps的Genymotion模拟器上进行测试时,我得到了null
。我不得不打开谷歌地图等谷歌应用程序以更新Google Play服务。之后它运作良好。
答案 1 :(得分:1)
请注意,getLastLocation(GoogleApiClient)始终可以使用 即使此方法返回true(例如位置设置),也返回null 在电话之间被禁用了。
因此,有很多理由可以获得null。我的建议是您检查权限,并确保允许位置权限,不仅要检查GoogleClient是否已连接且位置是否可用。您可以使用以下功能。
public static boolean checkAppPermissions(Context context, String... strPermissions) {
for (String permissions : strPermissions) {
if (!FrameworkUtils.isStringEmpty(permissions)) {
int result = ContextCompat.checkSelfPermission(context, permissions);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
}
}
}
return false;
}
你可以这样称呼它
checkAppPermissions(mContext, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)