Android:使用GoogleApiClient

时间:2016-09-26 19:55:21

标签: android android-service google-api-client google-location-services

您好我目前正在尝试使用GoogleApiClient获取Android设备的纬度和海拔高度值。我一直在这里关注指南:

GoogleApiClient: Last Known Location Guide

我也尝试从我的服务而不是活动中执行此操作,这里是我的代码片段以供参考:

public class AppService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient googleApiClient;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    googleApiClient.connect();
    try {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        Log.d("location", String.valueOf(lastLocation.getLatitude()));
        Log.d("location", String.valueOf(lastLocation.getLongitude()));
    } catch (SecurityException e) {
        Log.e("Location error", "Location object is null.");
    }

    googleApiClient.disconnect();

    //Stop service once it finishes its task
    stopSelf();
    return Service.START_STICKY;
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

每当我尝试访问Location变量以获取纬度和海拔高度时,我都会得到一个NullPointerException,任何想法为什么?

还想包含我的AndroidManifest文件以防万一,据我所知,我拥有所需的权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="app"
      android:versionCode="1"
      android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="@string/app_name" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </activity>
    <receiver
            android:name=".AutoStart"
            android:enabled="true" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>
    <service android:name=".AppService"/>
</application>
</manifest>

1 个答案:

答案 0 :(得分:1)

根据文档,对googleApiClient.connect()的调用是异步的:

  

public abstract void connect()

     

将客户端连接到Google Play服务。此方法返回   立即,并在后台连接到服务。如果   连接成功,onConnected(Bundle)被调用并入队   项目被执行。失败时,onConnectionFailed(ConnectionResult)   被称为。

     

如果客户端已连接或已连接,则此方法可以   什么都没有。

因此,您应该等待onConnected回调执行,并将您的位置检索代码放在那里。

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
  if (googleApiClient == null) {
     googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
  }
  googleApiClient.connect();
  return Service.START_STICKY;
}

@Override
public void onConnected(@Nullable Bundle bundle) {
  try {
    Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    Log.d("location", String.valueOf(lastLocation.getLatitude()));
    Log.d("location", String.valueOf(lastLocation.getLongitude()));
  } catch (SecurityException e) {
    Log.e("Location error", "Location object is null.");
  }

  googleApiClient.disconnect();
  stopSelf();
}