Continuous location updates in background

为君一笑 提交于 2019-11-30 22:34:26
Alon Levanon

Try this:

@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);
 }

replace your onStart with:

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

and:

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

Invoke your service:

startService(yourServiceIntent);

You can also check my code here

Is it working fine in background? Service does not stops after 45 mins while running in the background ? – Noman Nov 3 '15 at 6:18

It's a good comment. I had some proglem with the location update long continious in my project. And it really stopped after 45 minutes.

My service is foreground. I using

StartForeground(ServicesId.Push, notification);

And I every 45 minutes wake up location update

_timer = new Timer(); _timer.Schedule(new TimerTaskTrek(this), 45 * 60 * 1000 + 10 * 1000, 45 * 60 * 1000 + 10 * 1000);

And In timerTask

try {

Looper.Prepare();

} catch (Exception e) {

}

_client = new >GoogleApiClient.Builder(this).AddApi(LocationServices.API) .AddConnectionCallbacks(this) .AddOnConnectionFailedListener(this) .Build();

_client.Connect();

It's very simple and it's work very good. Enjoy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!