My app provides users location relevant notifications which means I need to be aware of my users' locations as real time as possible and not putting too much stress on battery.I have researched a bit and create the following list of option
partial Wakelock
: which lets the screen to timeout but CPU keeps executing task. But I just want my background code to be invoked every n seconds,check for location update,if the location is changed then send it to server.
AlarmManager
: I can use this to design recurring tasks but not sure if this will keep running in background indefinitely and can it be killed by users deliberately.
I want my background code to be invoked every n seconds as long as the app is installed on user's phone. I am looking for theoretical answers not the actual code as I need to understand what I am doing.
Yo can use Service class as follows ,
public class StartService extends Service {
Timer timer = new Timer();
private final int TIME_INTERVAL = 10000;
GPSTracker GPSTracker;
Double latitude ;
Double longitude ;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
GPSTracker = new GPSTracker(StartService.this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
doTimerThings();
return super.onStartCommand(intent, flags, startId);
}
private void doTimerThings()
{
timer.scheduleAtFixedRate(new TimerTask() {
@SuppressLint("DefaultLocale")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void run() {
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
// you get the lat and lng , do your server stuff here-----
System.out.println("lat------ "+latitude);
System.out.println("lng-------- "+longitude);
}
}, 0, TIME_INTERVAL);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}