没有获得后台服务的经度和经度

时间:2016-11-11 18:59:42

标签: android google-maps geolocation android-gps

我是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);
}

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;

    }
}

请帮帮我

1 个答案:

答案 0 :(得分:0)

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)

这将取代您当前的计时器机制。