没有从后台服务获取纬度和经度
Posted
技术标签:
【中文标题】没有从后台服务获取纬度和经度【英文标题】:Not getting latitude and longitude from background service 【发布时间】:2017-03-26 01:37:46 【问题描述】:我是 android 新手,我想在后台运行一项服务,并在 10 分钟后获取纬度和经度或地理地址并发送到服务器。
请帮帮我。
这是我的代码:
活动中
public void serviceCall()
Log.e("INSIDE ALARM", "INSIDE ALARM");
Intent intent = new Intent(getApplicationContext(), MyService.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyService.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
6000, pIntent);
在 Reciver 中
public static final int REQUEST_CODE = 9411;
@Override
public void onReceive(Context context, Intent intent)
Intent inti = new Intent(context, LocationService.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(inti);
在 IntentService 中
protected void onHandleIntent(Intent intent)
Log.e("imsidehandler Service", ":=");
mRequestingLocationUpdates = false;
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
checkLocationSettings();
sendDataServer();
public void onConnected(Bundle bundle)
if (mCurrentLocation == null)
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
public void onConnectionSuspended(int i)
public void onLocationChanged(Location location)
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
public void onConnectionFailed(ConnectionResult connectionResult)
private synchronized void buildGoogleApiClient()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
private void createLocationRequest()
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
private void buildLocationSettingsRequest()
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
private void checkLocationSettings()
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
protected boolean startLocationUpdates()
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return true;
return false;
protected void stopLocationUpdates()
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this).setResultCallback(new ResultCallback<Status>()
@Override
public void onResult(Status status)
mRequestingLocationUpdates = false;
);
private void updateLocationUI()
if (mCurrentLocation != null)
updateCityAndPincode(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
private void updateCityAndPincode(double latitude, double longitude)
try
Log.e("latitude","==>"+longitude);
Log.e("longitude","==>"+longitude);
this.latitude = latitude;
this.longitude = longitude;
getGeoAddress(latitude, longitude);
catch (Exception e)
private void getGeoAddress(Double latitude, Double longitude)
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String result = null;
List<Address> addressList = null;
try
addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0)
Address address = addressList.get(0);
Log.e("address","==>"+address);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
result += address.getAddressLine(i);
result += " ";
if (result.contains("null"))
result1 = result.replace("null", "");
catch (IOException e)
e.printStackTrace();
public void onResult(LocationSettingsResult locationSettingsResult)
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode())
case LocationSettingsStatusCodes.SUCCESS:
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try
status.startResolutionForResult((Activity) getApplicationContext(), REQUEST_CHECK_SETTINGS);
catch (IntentSender.SendIntentException e)
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
请帮帮我
【问题讨论】:
具体的问题是什么? Service 不是基于基于 AlarmManager 的定时器机制运行的吗?还是它运行了,但您只是没有收到有效的位置? 【参考方案1】:getLastLocation()
方法只是获取设备碰巧知道的最后一个已知位置。有时设备不会“碰巧知道”它的位置并返回null
。
设备不会自行确定其位置,而是仅在某些应用程序请求位置时确定。因此,您的应用现在依赖于请求位置更新的其他应用。
这里的“最后已知位置”也意味着:它可能不是最新的。位置确实带有时间戳,可用于评估该位置是否仍然相关。
我在您的代码中的任何地方都没有看到对requestLocationUpdates()
的调用。这将按照您可以指定的时间间隔请求最新的位置更新。
您的onConnected()
方法可能有:
public void onConnected(Bundle bundle)
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
(可以删除getLastLocation()
调用。)
您的IntentService
可以实现LocationListener
并执行与onConnected()
现在相同的操作,但只有在位置更新到达之后:
@Override
public void onLocationChanged(Location location)
// Cancel the updates after the first one:
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
这将是通过最小的代码更改请求和处理位置更新的方式。
当然还有其他方法,例如每 10 分钟请求一次更新并通过PendingIntent
处理它们。有this version of requestLocationUpdates() 需要PendingIntent
:
public abstract PendingResult<Status> requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
这将取代您当前的计时器机制。
【讨论】:
以上是关于没有从后台服务获取纬度和经度的主要内容,如果未能解决你的问题,请参考以下文章