我遇到Android Fused Location API问题。我有一个IntentListener服务,我需要定期接收位置。我成功创建并连接了GoogleApiClient,然后我通过PendingIntent请求接收位置更新,但每次调用GeofencingEvent.getTriggeringLocation
时,返回值始终为null。
以下是代码:
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationListener(Context context) {
if (!isGooglePlayServicesAvailable(context)) {
Log.d(TAG, "No Google Play Services.");
return;
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
private void startLocationUpdates(Context context) {
Intent i = new Intent(context, IntentListener.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
com.google.android.gms.common.api.PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, pi);
Log.d(TAG, "Location update started ..............: ");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "INTEEENT");
String action = intent.getAction();
if(Actions.ACTION_START_INTENT_LISTENER.equals(action)) {
init(this);
}
else {
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
if(event == null) Log.d(TAG, "Null event");
if(event.getTriggeringLocation() == null) Log.d(TAG, "null location"); // **<-- PROBLEM HERE**
if (event == null || event.getTriggeringLocation() == null) {
return;
}
Location location = event.getTriggeringLocation();
Log.d(TAG, "LocationC: " + location.getLatitude() + ", " + location.getLongitude());
}
}
这是清单
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.srn.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name="com.srn.app.IntentListener"></service>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
我在安装了Android 5.1的x86模拟器中运行该应用程序。
知道可能是什么问题吗?
感谢。
答案 0 :(得分:1)
Geofencing API必须通过GeofencingApi.addGeofences()专门注册。假设您确实希望从正在进行的requestLocationUpdates()
来电中收到位置信息,则应使用LocationResult.extractResult()代替GeofencingEvent.fromIntent()
。
旧版Google Play服务的另一种选择是使用密钥KEY_LOCATION_CHANGED从意图中提取一个位置:
Location location = intent.getParcelableExtra(
LocationServices.FusedLocationProviderApi.KEY_LOCATION_CHANGED);