4

Я разрабатываю приложение, которое будет непрерывно отправлять обновления местоположения из службы фона. Я пробовал следующий код.Непрерывное обновление местоположения в фоновом режиме

public class LocationService extends Service implements LocationListener, 
GooglePlayServicesClient.ConnectionCallbacks, 
GooglePlayServicesClient.OnConnectionFailedListener { 
    LocationRequest mLocationRequest; 
    LocationClient mLocationClient; 
    @Override 
    public void onCreate() { 
    //creating log file in mobile 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service created:", com.example.locationservice.Constants.LOG_FILE); 

     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setInterval(5*1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    // mLocationRequest.setFastestInterval(5*1000); 
     mLocationClient = new LocationClient(getApplicationContext(), this,this); 
     mLocationClient.connect(); 

    } 
    @Override 
    public void onStart(Intent intent, int startId) { 
     int start = Service.START_STICKY; 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service Started:", com.example.locationservice.Constants.LOG_FILE); 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     // TODO Auto-generated method stub 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Connection to client failed", com.example.locationservice.Constants.LOG_FILE); 
     this.stopSelf(); 

    } 

    @Override 
    public void onConnected(Bundle arg0) { 
     // TODO Auto-generated method stub 
     Log.i("info", "Location Client is Connected"); 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Client Connectd:", com.example.locationservice.Constants.LOG_FILE); 
     //checking for locaton enabled or not 
     if(Util.isLocationEnabled(getApplicationContext())){ 
     //checking for internet available or not 
      if(Util.isInternetOn(getApplicationContext())){ 
       mLocationClient.requestLocationUpdates(mLocationRequest, this); 
      }else{ 
       Log.i("info", "Internet not available"); 
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Internet not available", com.example.locationservice.Constants.LOG_FILE); 
       this.stopSelf(); 
      } 
      }else{ 
      Log.i("info", "Location Acess disabled"); 
      appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Acess disabled", com.example.locationservice.Constants.LOG_FILE); 
      this.stopSelf(); 
      } 
      Log.i("info", "Service Connect status :: " + isServicesConnected()); 

    } 

    @Override 
    public void onDisconnected() { 
     // TODO Auto-generated method stub 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Client DisConnectd:", com.example.locationservice.Constants.LOG_FILE); 
     Log.i("info", "Location Client is DisConnected"); 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     double latitude = location.getLatitude(); 
      double longitude = location.getLongitude(); 
      appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Changed:", com.example.locationservice.Constants.LOG_FILE); 
      Log.i("info", "Latitude :: " + latitude); 
      Log.i("info", "Longitude :: " + longitude); 
      if(Util.isInternetOn(getApplicationContext())){ 
      //sending location details 
      sendLocation(location); 
      }else{ 
       this.stopSelf(); 
       Log.i("info", "Internet not available"); 
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Internet not available", com.example.locationservice.Constants.LOG_FILE); 
      } 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     Log.i("info", "Service is destroyed"); 
     mLocationClient.removeLocationUpdates(this); 
     appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service Destroyed:", com.example.locationservice.Constants.LOG_FILE); 
     super.onDestroy(); 
    } 
    private boolean isServicesConnected() { 
      // Check that Google Play services is available 
      int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(LocationService.this); 
      // If Google Play services is available 
      if (ConnectionResult.SUCCESS == resultCode) {   
      return true; 
      } else { 
      return false; 
      } 
     } 
} 

но onLocationChanged звонит только тогда, когда я приложение открытой компании встроенной карты. В противном случае он не обновляет данные о местоположении. Я начал эту услугу из-за действия с помощью службы оповещения. alarmManager триггеры на каждую минуту. может ли кто-нибудь сказать мне, почему onLocationChanged не звонит непрерывно.

Заранее спасибо.

+0

Уверены, что устройство успело получить первое исправление GPS (как вы ожидаете высокой точности). Если это вас беспокоит, вы можете попробовать мой код из этого ответа http://stackoverflow.com/questions/19365035/location-servise-gps-force-closed/19366773#19366773. Успешно использовали это несколько раз. – cYrixmorten

ответ

2

Попробуйте это:

@Override 
public void onCreate() { 
//creating log file in mobile 
    appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service created:", com.example.locationservice.Constants.LOG_FILE); 

    mLocationClient = new LocationClient(getApplicationContext(), this,this); 
} 

заменить OnStart с:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
mLocationClient.connect(); 
} 

и:

@Override 
public void onConnected(Bundle arg0) { 
mLocationRequest = LocationRequest.create(); 
mLocationRequest.setInterval(5*1000); 
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
mLocationClient.requestLocationUpdates(mLocationRequest, this); 
} 

Вызывать ваш сервис:

startService(yourServiceIntent); 

Вы также можете проверить мой код here

+0

Работает ли он в фоновом режиме? Сервис не останавливается после 45 минут во время работы в фоновом режиме? – Noman

0

Работает ли он в фоновом режиме? Служба не останавливается после 45 минут во время работы в фоновом режиме? - Noman 3 нояб. 15 в 6:18

Это хороший комментарий. У меня был некоторый проглм с обновлением местоположения, который долгое время оставался в моем проекте. И это действительно остановилось через 45 минут.

Мое обслуживание на переднем плане. I с использованием

StartForeground (ServicesId.Push, уведомление);

И каждые 45 минут просыпаются обновление местоположения

_timer = новый таймер(); _timer.Schedule (новый TimerTaskTrek (это), 45 * 60 * 1000 + 10 * 1000, 45 * 60 * 1000 + 10 * 1000);

И В TimerTask

попробовать {

Looper.Prepare(); 

} поймать (Exception е) {

}

_client = новый> GoogleApiClient.Bu ilder (this) .AddApi (LocationServices.API) .AddConnectionCallbacks (this) .AddOnConnectionFailedListener (this) .Build();

_client.Connect();

Это очень просто и работает очень хорошо. Наслаждайтесь

 Смежные вопросы

  • Нет связанных вопросов^_^