Android - Make app send heartbeat to server - java

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!

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:
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.

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

Related

Retrieve service closing time?

I want to restart my service with new data, what allows me to release every objects in service without making complicated communication between Fragment<>Service.
I tried this, everything works:
if(isMyServiceRunning(PlayerService.class))
{
getActivity().stopService(intenx);
positionTemp--;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
getActivity().startService(intenx);
positionTemp++;
}
}, 500);
}
else{
getActivity().startService(intenx);
}
}
});
But I don't know if I should to worry about closing time in different devices? Is there possibility than service will be closing longer than 500ms? My Motorola takes 300ms to close service and then I can re-run it without problem.
Any advice? Communication with service isn't really easy, it's music player with almost 15 different controls, etc. I think that the easiest way is just stop current service and restart with new entry variables.
That seems unnecessary, and it'll add a 500 ms lag to any user actions. A Service can accept multiple intents without stopping and starting again. Just handle each new intent in onStartCommand(). You don't need any complicated communication between the fragment and service; the fragment just needs to forward every request to the service and let the service do its thing. Although for a better UI you might need to bind to the service so it can update the UI based on the service's state.

Long network operation needs to update the UI in Android many times

my Activity shows to the user some data, which are download from a web server. Data could change over the time, so the web server communicates new updates to the connected clients.
So the work of my application is basically this:
while ( true ) {
wait for updates;
update the UI;
}
This code could run forever, and during its life it should update the UI many times.
What class should I use to implement this code?
Thread or Runnable seems the easiest solutions to my problem, but how could I comunicate to the UI thread?
onServerChangesListener... refresh UI
public void serverStateWrappr(){
Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_localstr = getStuff((String) msg.obj)
updateAdapter(_localstr)
}}
from the thread which has a handleRef ...
while (onChangesForClient) {
Message msg = Message.obtain();
msg.what=1;
msg.obj=newData;
//TODO this is the comment for UI
mhandleRef.sendMessage(msg);
}
}
You should probably go with an asyncTask, calling runOnUiThread when you need to update the UI. Have a look to this question to see how activity.runOnUiThread() should be used
IMHO AsyncTask is preferrable, because it gives you more fine-grained control over your background task via onPreExecute(), onPostExecute()

How Do I periodically Check For Updates on a Parse Server? [duplicate]

This question already has an answer here:
How to call asyncTasks periodically
(1 answer)
Closed 8 years ago.
Helly Community. I´m fairly new to Android and probably the biggest noob when it comes to networking and backend.
Right now I´m having following problem.
I´m building a simple chatting application and want my app to check the Parse server for a specific message parseobject.
Getting the Objects, working with them and deleting them works fine.
If i do it only once.
This is how I get messages from the Cloud and add them to my App Layout.
ParseQuery<ParseObject> query = ParseQuery.getQuery("message");
query.whereEqualTo("recipient", getRemote_id());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> messages, ParseException e) {
if(messages != null){
Iterator itr = messages.iterator();
while(itr.hasNext()){
ParseObject message = (ParseObject)itr.next();
addMessageToLayout(message.getString("text"), "in", "new", "");
try {
message.delete();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
I want my app to check for new messages the whole time.
Ive tried with AsyncTask and a while(true) loop. The loop constantly creates new asynctask objects.
As result the app doesn´t react anymore and crashes.
When I use an instance of the runnable class im getting following error: NetworkOnMainThreadException, and the App crashes.
Because of this error i tried using asynctask in the first place. Isn´t a runnably object running on a different thread than the main thread as well?
I tried putting the thread to sleep for some seconds, still the app crashes in case of the async task.
Could the Problem be following: Im using anoher runnable object to update some animation in my app.
I also tried not using any kind of threading as the parse methods already work in background so they probably dont even need one. Again the app crashes because of an NetworkOnMainThreadException.
///_////
The weirdest thing comes now. If i´m not using a loop, and just check for messages when i enter the activity at first i´m getting an NetworkOnMainThreadException, but then the application somehow recovers into the newly opened activity and loads my messages from the server.
During that time of course the UI is blocked though. Still, thats the only way i can get it to work right now.
Doing it with a Handler and the TimerTask works, I can´t seem to close the thread when i exit the Activity though.
Here my code:
public void startLookingForMessages(){
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new GetMessagesTask().execute();
}
});
}
};
timer.schedule(task, 0, 1000);
}
I found out that im getting the NetworkOnMainThreadException only if i´m trying to shut down the thread or close the while loop when calling onStop(). If I let the thread do its own thing, that means not putting in any code to stop it any time, my app works fine.
How could i overcome this problem?
I know this is getting kinda long. But maybe someone has the same Problem and can get some Info here.
Thanks you for your help already =)
Don't do it this way. Just don't.
Think about it: you're calling an AsyncTask to check periodically if something is there. Now, that gets to be quite expensive. Think about the battery and network resources you waste if that message is not there. Therefore, you waste a lot of resources. It's not a good idea to do it like this. You waste the user's resources. In addition, you also need a service to run in the background, as your app will not always be running.
A good way to solve this is to use Google Cloud Messaging. So what Google Cloud Messaging does is it "pings" a device every time there's an update. This makes life easier on you, as you only need to check if your app has received one of these pings, and it also saves battery and network resources.
If you're using PHP for your server-side application, you can use this to get started with GCM and PHP: GCM with PHP (Google Cloud Messaging)
This page on Google's website should also help with implementing it.
By using GCM, you'll also avoid having infinite loops or checking for more information every x minutes. You don't have to check yourself if new information is available; it'll ping you when it's available.

More and more Threads are causing my app to lag

In my app I got some activities and a ReceiverThread.class.
The Thread is started from two different activities. And everytime I switch to another Activity and recall the former active Activity it starts a new Thread. So if I do some test on my app for about 10 Minutes or the app is simply used for some time, there is a mass of Threads open and all do the same.
Most of the time the Threads are on TimedWait.
This gives me wrong data and causes the app to lag hard, sometimes its not even responding.
Is there a good possibility to stop a thread onPause() or onStop() ? Because many of the methods are deprecated. Or how to resume a previous started Thread and so prevent the Activity from creating a new one?
This is my ReceiverThread.run():
public void run() {
initiateCAN();
while (true) {
try {
Thread.sleep(60);
mHandler.post(r);
} catch (InterruptedException e) {
break;
}
}
}
If something is not clear or missing, please feel free to ask and I will edit my post, but don't just simply downvote.
The recommended way to do this is to use the built-in interrupt system. You can then stop the thread by calling Thread.interrupt() (best in onPause() if you don't want multiple instances). Your run method would need to be somewhat changed:
public void run() {
initiateCAN();
try {
while (!isInterrupted()) {
Thread.sleep(60);
mHandler.post(r);
}
} catch (InterruptedException e) {
}
}
While this might work, it's still better to use a Service or another way to make sure there is only one instance at one time (maybe fragments instead of activities?).
You can use Android Services, and that service starts the thread. When you switch the activity, the services is running and not is necessary start a new thread.

Update UI from a background worker

I want to port my client from Java Swing(Java client) to Android(Android client).
Basically, my Java client have a thread, which run a forever while loop to receive UDP packets, and base on content of UDP packets, UI of the corresponding JFrame will be updated.
Now I want my Android client has a background worker like the thread in the Java client, and that worker will be initialized in the main activity. Then when there are some requests from the UDP socket, the main activity will start some corresponding activities (Chat Activities), then there are some other requests come from the UDP socket, the worker will update on the activity(this activity can be main activity or a Chat Activity) which is being displayed on the screen.
So my question is what the background worker should be:
Service
Normal Java thread
Asynctask
or what...
Which is the most appropriate with my requirements?
Thanks!
The background worker should be a service, because
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.
while your UI will be a activity, your service will read the UDP packets and the activity will be modified accordingly.
A Service is the most suitable candidate in your case.
There is a class Application class for each android application . First extend it and it will be initialized on very first time your app will start even before your Activity . Initialize/ start your normal java thread to perfrom background work here . The key advantage will be you can get instance of this application class anywhere from the app (It means you can control on the background thread from anywhere in the applicaion . Send background http request etc.. whatever ....) .Then initialize the handler on the UI thread of particular activity upon which you want to do changes and do something like this.
private Handler myHandler ;
public void checkBackgroundAndUpdateUi()
{
if(conetxt.getApplicationContext().getStatus == completed)
{
initializeHandler();
handler.postRunnable(myRunnable);
}
}
Runnable myRunnable = new Runnable(){
public void run()
{
// update your UI views here .....
}
};
private void initializeHandler(){
myHandler = new Handler ();
}

Categories

Resources