Continuous location updates in background

后端 未结 2 1760
一向
一向 2021-01-06 06:23

i am developing a application which will send location updates continuously from a background service. i tried following code.

public class LocationService e         


        
相关标签:
2条回答
  • 2021-01-06 06:54

    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

    0 讨论(0)
  • 2021-01-06 06:54

    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

    0 讨论(0)
提交回复
热议问题