2

I need to implement a regular heartbeat.

The heartbeat itself is a simple HTTP-GET call to my server.

The thing is I want to send it as long as my app is open. When I close the app the sending should stop.

I read a few things about Services and AlarmManager but how can I call/stop them when navigating through my app activities?

This also seems nice but still the same problem:

final Handler handler = new Handler();
Runnable runable = new Runnable() {

@Override
public void run() {
    try{
        //do your code here
        //also call the same runnable 
        handler.postDelayed(this, 1000);
    }
    catch (Exception e) {
        // TODO: handle exception
    }
    finally{
        //also call the same runnable 
        handler.postDelayed(this, 1000);
    }
}
};
handler.postDelayed(runable, 1000); 

Could anybody maybe post a good example or a link?

Thanks!

Community
  • 1
  • 1
Ron
  • 22,128
  • 31
  • 108
  • 206

2 Answers2

1

The thing is I want to send it as long as my app is open. When I close the app the sending should stop

In android a bit harder than in iOS, but lets do it: In Android you don't have a callback at application level when the app it goes to background or is killed. Instead of thins you should handle at each Activity onStop Method for example. Take a look at Activity lifecycle: enter image description here

or onDestroy method. Note: When an activity it isn't visible anymore it can be because your app is gone to background, closed or other activity is visible. You have to decide which case is and use your HTTP Get / Post, or stop it , when needed.

Here is a sample code with Async task to send data over HTTP.

Community
  • 1
  • 1
0

I implemented a simple timeout using a similar Handler to your code. When an Activity calls onPause trigger the timeout on a 10 second delay, when an Activity calls onResume cancel that call with removeRunnable(...) if the timeout code fires you know the user has left your app (this is the reason for the 10 second timeout, to give a new Activity time to launch if there is one).

You could add something in your timeout code to kill the heartbeat. e.g. cancel the heartbeat Runnable

ScouseChris
  • 4,377
  • 32
  • 38