android - Checking the location every 10 minutes in the background -
my requirement check location of device every 10 minutes using background service. basic gist of should happen every 10 minutes -
- start service.
- wait minute (maximum) listener location, once location taken, remove listener , stop service.
- if listener doesn't respond, use getlastknownlocation(), remove listener , stop service.
- if gps off, reports app (this step working fine)
what have tried doing till -
- made service triggered every 10 minutes using alarmmanager
- added location listener inside service.
- onlocationchanged() locationlistener has method - stopself() included, service ends after receiving location. however, method called numerous times. checked while debugging. because there many instances of onlocationchanged() called ?
i don't need entire code answer, rather appreciate strategy should adopt fulfil requirements without hurting battery much. approach, unless , until location found, gps remains on draining battery constantly.
instead of alarm manager scheduling each 10 min, use fusedlocationapi , location request in order accurate location.
locationrequest mlocationrequest = locationrequest.create(); mlocationrequest.setpriority(locationrequest.priority_balanced_power_accuracy);//change priority_high_accuracy more accurate. mlocationrequest.setinterval(600000); // update location every 10 minute locationservices.fusedlocationapi.requestlocationupdates( mgoogleapiclient, mlocationrequest, this);
call method whenever need location
/** * location detail fused location api. * @param mcontext * @return */ private location getlocationdetails(context mcontext) { location location = null; if (mgoogleapiclient != null) { if (activitycompat.checkselfpermission(mcontext, manifest.permission.access_fine_location) != packagemanager.permission_granted && activitycompat.checkselfpermission(mcontext, manifest.permission.access_coarse_location) != packagemanager.permission_granted) { log.d(tag,"location permission denied"); return null; }else { location = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient); } } return location; }
Comments
Post a Comment