简体   繁体   中英

Get Location Periodically Using Background Services,Save In Local Database in Android

1.In My application ,I want to track User Current Location Every 1 minute then Save in Local Database. Not getting Proper location Some times ,when user is Walking .

2.For finding location ,I want to use Google play Services API.

My Need:

Background Service Should get the location, save in local Database every minute.Even Application is Closed.

also with low Battery Usage .

I tried Some codes some methods are deprecated and not Working.

Please Suggest me any solution.

This is one of the way you can achieve it, make your service class like below

here,

with this ScheduledThreadPoolExecutor your service will be on in background and you will need LocationManager

your SERVICE.class extend Service implements LocationListener, Runnable

    private LocationManager mgr = null;
    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);



        @Override
         public void onCreate() {
                 //check gps is on/off
                 //get locationmanager
          }

         @Override
         public int onStartCommand(Intent intent, int flags, int startId) {
                  //check if internet is on/off
                  setBeforeDelay15();
                  return super.onStartCommand(intent, flags, startId);
         }

         @Override
         public void onLocationChanged(Location location) {
                   //re-execute at time you need with **scheduleAtFixedRate**
         }

         @Override
         public void run() {
                 //here get the best location from two ways 1>gps and 2>network provider
                 //once you get this insert to database
                 //set delay then request call method  again
         }

          @Override
          public void onDestroy() {
                //if locationmanager is not null then remove all updates
          }

         private void setDelay15() {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {             
                    // Log.e("srop self by", "delay15");   
                    startWork();           
                }
            }, 300000);//120000
        }

private void startWork() {
//check here for 1>gps and 2>network provider
//get location and save it
}

use this , when you require location in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM