i am developing an android app to show notifications.How can i poll a webservice at finite interval (say 10 min interval) to check for any update and show as notification in android notification panel.
You do not need a service. I feel like a broken record. In this use case a service will sit there for 95% of the time doing nothing but still using system resources and more importantly drain the battery.
Please see my answer on a similar question that uses an Alarm from the AlarmManager:
Running task periodicaly(once a day/once a week)
Edit:
Look at this tutorial from the Android Development site for how to implement notifications: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
There is Cloud to Device Messaging service provided by Google C2DM . You can use this service to push message into all registered mobile devices. This not only improves performance but also makes sure that the Battery is not drained while continuously polling the server.
For your scenario, you can write in a java class to regularly poll the web service and use C2DM service to push the message to your Android phone which can be shown as a Notification. Check out this tutorial by Vogella on link. Or better, if you are using the web service just for fetching updated details, then you can avoid the web service and directly call the C2DM Push Service to push message to all registered devices whenever there is a change.
Hope this helped. :)
use timer in which you can call to that web service after finite interval for e.x
Timer waitingTimer = new Timer();
waitingTimer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
// code to hit xml after time interval
}
});
}
},0,20000); // mention time interval after which your xml will be hit.
Here 20000 means after every 20 sec it will be hit.
Define a service, having a thread with a timer, on timeout invoke webservice.
Related
I have a business requirement that the Android app needs to report to the server every few seconds (all the time, 24/7) on a dedicated device.
First I thought that it can be done with the PeriodicWorkRequest, but I've read its minimum interval is 15mins.
What would be the best way to achieve this? What mechanism I can rely on to be sure that the process won't be killed?
Is it possible to do with WorkManager? Should I have a foreground service with a loop?
I think you could schedule it the other way. Make your server send a notification to your android device,could be done easily via firebase. Then handle notification in your app and report back to the server.
What is the best way to repeat a task on android with a short period (for example 2 seconds)? It must keep running even if the screen is locked. If I am not mistaken only the AlarmManager can be used for it because it wakes up the phone from sleep but it should not be used for such a short period (recommended minimum 1 minutes) because it drains your battery and uses too much resource. So what type of notification tool is used by chat programs like Facebook Messenger or Skype to keep the user notified in every second of a day?
Thank you in advance.
So what type of notification tool is used by chat programs like
Facebook Messenger or Skype to keep the user notified in every second
of a day?
They use the concept of push notification. Basically there is a service running in the background which listens to the server for any new data. When server has a new data it 'pushes' it to the client and the service handles the data and displays it as a notification.
If you're a beginner then you should look into FireBase as a starting point for implementing push notification.
this is one option to you,check may be helpful
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// your code which you want to repeat
}
}, start_task_after_some_milli_seconds, repeat_time_in_milli_seconds);
When you want to stop
then call timer.cancel() method
I have an application for android 4.0(android:minSdkVersion="14") with lots of SQLite tables that needs to download(not delete or send) new data from my server. At the moment the user has a sync button, however i would like to implement something that would synchronize automatically when 3G/Wifi is on and every 1-2 hour.
What pattern or best practice should i use? an Alarm thing, or a local service, or a remote service, or something else?
You need two things:
An alarm (Have a look at tutorials about the AlarmManager) to run your code every 1-2 hours
A broadcast receiver to intercept network events. (see for instance BroadcastReceiver when wifi or 3g network state changed)
Make sure your code runs in his own thread, you don't want to execute anything heavy in the broadcast receivers. A good place to run such a code would be a service with his own separate Thread.
Use a service and a broadcast receiver (for the wifi state, as mentioned above). Remember that polling a web-server every X times is a really bad experience in terms of battery usage. Try building a GCM web service.
I would recommend you read Chapter 19 of Android Pro 4( http://my.safaribooksonline.com/book/programming/android/9781430239307/chapter-19-broadcast-receivers-and-long-running-services/navpoint-164 ) and then use the already ready source code from here http://www.androidbook.com/akc/filestorage/satya/documentfiles/3810/ProAndroid4_Ch19_TestReceivers.zip
I did this by using Alarm + ALongRunningReceiver(=Broadcast Receiver) + ALongRunningNonStickyBroadcastService(Local Service) + LightedGreenRoom(Handles CPU partial_wake so it doesn't fall asleep).
I have an asynctask which retrieve data from webserviece. I want to run this task every 5 minutes to get the updated data from the server, but till now I don't know how can I do it.
I tried this code but my AsyncTask didn't stop
//...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new AddStringTask().execute();
}
}, 0, 5000);
As being suggested from others, you should use Push (GCM) instead of Poll. taken from this say:
Poll might easy to implement, but you will never be actually
real-time. If you polling interval is 30 min, you can get a message
that is 29 minutes and 59 seconds late. Moreover, polling more often
than every 15-30 min will kill your battery pretty quickly:
https://labs.ericsson.com/apis/mobile-java-push/blog/save-device-battery-mobile-java-push
As Michal K said, you can use AlarmManager with a Service and/or BroadcastReceiver to wake your app periodically.
However, in order to preserve the user's battery I highly recommend not polling the connection.
Instead, you can use Google Cloud Messaging for Android or GCM (formerly called C2DM)
Here's the site:
http://developer.android.com/guide/google/gcm/index.html
EDIT
The main benefit here is that Android phones that have Google accounts will already poll Google's servers periodically. They do this with cooperation from the carriers (like Verizon/AT&T). Because of this, the radio can go into low power mode and receive push notifications. By using Google's service, you enable a way for your app to receive data via push notifications without causing any extra battery drain.
====================
(Also, here is some of the info from my other post about this).
There was a very interesting Google IO talk this year about how the cell radio sits in an idle/low-power state most of the time, and takes a few seconds to "warm up". They also discuss the perils of how polling the internet periodically will really drain the battery.
http://www.youtube.com/watch?v=PwC1OlJo5VM
Battery talk starts about 17:12
http://www.youtube.com/watch?v=PwC1OlJo5VM&feature=player_detailpage#t=1032s
A slide from the presentation:
Take the Gmail app as an example. Whether the phone is on or not, it polls every 10 minutes or so to download new emails which may have arrived since you last checked.
I know how to create a new service and bind to it. But I can see a few ways to accomplish this:
Bind once, and have the service run in an infinite loop, sleeping for 10 minutes between each loop
Bind and unbind right when it's done, scheduling the next bind somehow in 10 minutes
Using the AlarmManager class to schedule future polls
What are the trade offs? How does the Gmail app accomplish it?
Thanks!
Gmail app uses pushing, not polling. I suggest using this technique instead, polling is a battery killer in mobile devices.
To implement pushing, take a look at C2DM.
If you still want to poll, the recommended way would be to set up a periodic alarm in the AlarmManager.
UPDATE: Google has deprecated C2DM and replaced it with Google Cloud Messaging (GCM)
UPDATE: Google has deprecated GCM and replaced it with
Firebase Cloud Messaging (FCM)
For a continuous, but not intensive poll like the one you comment (in the range of minutes between polls), I would implement it with AlarmManager. That way you make sure the phone wakes up to poll without the need for a wakelock, which would destroy your battery. As CommonsWare pointed out, you will still need to implement a wakelock for the time your code is executing, but you can release it as soon as the code is done, avoiding keeping the phone on while just waiting. See his comment for an example on how to implement it.
I would use a Service if, instead, you need faster polls during a shorter period of time (seconds between each poll), since setting alarms does not make sense to such short periods, and the battery would drain anyway.