У меня возникли проблемы с отправкой дополнительной строки с моим PendingIntent
, которую я передаю LocationServices.FusedLocationApi.requestLocationUpdates(GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
.
Похоже, что дополнительное имя пользователя, которое я помещаю в Intent
, искажает местоположение, которое requestLocationUpdates
пытается передать моему IntentService
, поскольку intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED)
возвращает null
.
ИЗМЕНИТЬ
Я попытался создать класс User
, реализующий Parcelable
, и добавить его как дополнительный:
mRequestLocationUpdatesIntent.putExtra("username", new User(username));
и я также попытался поместить Parcelable User
внутри Bundle
, как было предложено в комментарии к этому отчету об ошибке https://code.google.com/p/android/issues/detail?id=81812:
Bundle userBundle = new Bundle();
userBundle.putParcelable("user", new User(username));
mRequestLocationUpdatesIntent.putExtra("user", userBundle);
на моей службе:
Bundle userBundle = intent.getBundleExtra("user");
User user = userBundle.getParcelable("user");
String username = user.getUsername();
Однако ни один из этих подходов не имел никакого значения. Всякий раз, когда я добавляю какие-либо дополнительные данные в свое намерение, местоположение никогда не добавляется к намерению при обновлении.
Я настраиваю этот IntentService
для обработки обновлений местоположения:
public class LocationUpdateService extends IntentService {
private final String TAG = "LocationUpdateService";
public LocationUpdateService() {
super("LocationUpdateService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent");
Bundle extras = intent.getExtras();
Log.d(TAG, "keys found inside intent: " + TextUtils.join(", ", extras.keySet()));
String username = intent.getStringExtra("username");
if (username != null) {
Log.d(TAG, "username: " + username);
} else {
Log.d(TAG, "username: null");
}
if (!intent.hasExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED)) {
Log.d(TAG, "intent does not have location :(");
}
Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if (location == null) {
Log.d(TAG, "location == null :(");
}
Log.d(TAG, "latitude " + String.valueOf(location.getLatitude()));
Log.d(TAG, "longitude " + String.valueOf(location.getLongitude()));
...
}
}
Когда пользователь нажимает кнопку, в моей основной деятельности вызывается startLocationUpdates
:
основной вид деятельности:
...
Boolean mLocationUpdatesEnabled = false;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(LOCATION_UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
Log.d(TAG, "startng location updates...");
mLocationUpdatesEnabled = true;
if (mLocationRequest == null) {
createLocationRequest();
}
// create the Intent to use WebViewActivity to handle results
Intent mRequestLocationUpdatesIntent = new Intent(this, LocationUpdateService.class);
// create a PendingIntent
mRequestLocationUpdatesPendingIntent = PendingIntent.getService(getApplicationContext(), 0,
mRequestLocationUpdatesIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
// request location updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest,
mRequestLocationUpdatesPendingIntent);
Log.d(TAG, "location updates started");
}
protected void stopLocationUpdates() {
Log.d(TAG, "stopping location updates...");
mLocationUpdatesEnabled = false;
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient,
mRequestLocationUpdatesPendingIntent);
Log.d(TAG, "location updates stopped");
}
Все это работает хорошо и хорошо; Когда пользователь нажимает кнопку, вызывается toggleLocationUpdates
, который вызывает LocationServices.FusedLocationApi.requestLocationUpdates
, который вызывает мой LocationUpdateService
, где я могу получить местоположение.
Проблема возникает, когда я попытался добавить дополнительную строку в свой Intent
, используя Intent.putExtra(String, String):
основной вид деятельности:
...
protected void startLocationUpdates(String username) {
....
// create the Intent to use WebViewActivity to handle results
Intent mRequestLocationUpdatesIntent = new Intent(this, LocationUpdateService.class);
//////////////////////////////////////////////////////////////////
//
// When I put this extra, IntentService sees my username extra
// but the parcelableExtra `location` == null :(
//
//////////////////////////////////////////////////////////////////
mRequestLocationUpdatesIntent.putExtra("username", username);
...
}
...
ИЗМЕНИТЬ Я начал следующее предложение как утверждение, а не как вопрос: "Я использую..."
Использую ли я правильный подход к отправке дополнительных данных в эту обработку обновления местоположения IntentService
, или есть более разумный способ сделать это?
Это ошибка или просто плохая документация?
"location == null :("
, то естьhasExtra()
возвращаетfalse
, илиintent.getParcelableExtra()
просто возвращает ноль? - person ianhanniballake   schedule 23.06.2015java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
Я отредактировал IntentService, чтобы обеспечить подробное ведение журнала, которое показывает, чтоIntent.hasExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED
возвращает false,location == null
и создается исключение ссылки на нулевой объект. - person techjeffharris   schedule 23.06.2015keys found inside intent: username
; однако, когда я не указываю имя пользователя в намерении, я получаю этот вывод:keys found inside intent: com.google.android.location.LOCATION, com.google.android.gms.location.EXTRA_LOCATION_RESULT
- person techjeffharris   schedule 23.06.2015username
там не было. - person techjeffharris   schedule 15.08.2015