In my application I need to refresh my data in each 5s or 10s or 1 minute, according to my user preference.
I can create thread and use timer class but i want to know is there any other way? for example timer of system sends flag (broadcast something) and i get it in application (in order to refresh my data)?
Thanks
If you want to refresh the data every serval seconds, you can setup a Hanlder to do this. However, this requires your activity keeps running.
If you want to do something at a specific time, like an Alarm. You can use the AlarmManager. This would lauch your activity or other components even it is not running now.
If you just want to moniter the change in the system time. Well, there is a Intent ACTION_TIME_TICK . You can register a BroadcastReceiver to listent to it and implement your own code when the systemt brocasts it. However, the "TICK" interval is "One Minute" only and can not be changed.
AlarmManager is what you are looking for. It can be used to set up periodic events that are delivered via a PendingIntent (which can be turned into an Intent broadcast).
I would be wary checking for new data on such a regular interval unless the device is always connected to a power source, especially if you are making the check over a network. With that small a poll interval going to the nework the battery will be flat in hours.
Related
I am creating a notification app, which will alert user after they set a reminder notification. My current implementation logic is:
Create a Service, which starts running in background when user opens their app.
In onCreate() method of service, I am implementing a Timer task which will repeat after 5000ms interval and will call a method, which will check all reminders set by user and notify user if any reminder is set for current time.
I use broadcast receiver to run the service on Boot_Completed event, if in case user turns off their phone.
This implementation is working good, I have faced no issues with it, but my concern is that is this a good practice? Keeping in mind that service running and checking every 5 secs will consume battery. Also if user turns on Stamina Mode, Power saving mode or any such mode, will OS kill my service. Is there anything I can do to give priority to my Service not to be killed.
If there is any other more efficient way to implement this sort of task, I want to implement that in my project.
Looking forward for suggestions.
Much Appreciated.
best approach is wakeful intent service with alarm receiver as mentioned here
https://github.com/commonsguy/cwac-wakeful
all good but use AlarmManager.setRepeating() as timer. the intent come even if your app killed.
I'm looking to build something similar to Google's field trip application. The key attributes that I'm looking to prove out are:
A background "job" that runs every X minutes and checks the user's location and make a webservice call(this question doesn't really concern the location part)
The job should run even if the user exits the main application.
The background job should automatically start up after the device reboots.
After a reboot the application should not show up on the "recent/history" screen
My reading has brought me to a number of different classes/APIs from broadcast reciever of on boot, to regular services, to alarm manager, etc. It seems there are multiple ways this could be made to work, I'm curious what the community recommends as a high level approach?
You would definitely want to use a broadcast manager to get the boot event.
As far as polling for location goes, it sounds like you would want to use a Service and start it once you received the boot event.
Services
You could then use an event bus like Otto to communicate your events to wherever you need.
As far as the timing goes you could use a job manager to run things at various intervals, or just simply create a runnable and have it run as often as you like. As long as you keep it in the service, you should be able to control the length that it will run just fine. Regardless of whether or not the app is closed.
I think you may divide your solution into two parts :
Starting the app or the service after the device re-boot process completed by defining a Broadcast receiver that has the following action :
And on the "onReceive" method of the broadcast "do your task " start the service that listen to the location service updates.
For the part of listening to the location updated every x minutes, you would better use the alarm manager to "wake up" the service every x minutes, and every service sets the alarm for the next call.
I'm new to Android so I want to make sure that the following solution is the correct one.
The problem:
I want to sync the device's local database with a database on my server, via a webservice, every 10 minutes. I already have a web service call that I can make that returns the new/updated records. What I'm wondering is what is the best way to schedule this task. I want the databases to sync even when the application is not running.
My solution (is this the correct route to go?):
I will have one BroadcastReceiver that listens for android.intent.action.BOOT_COMPLETED, in it's onReceive I will create an AlarmManager that sends a message to MyReceiver (via a PendingIntent) every 10 minutes. Also, in my application's startup I will do the same (create an alarm to send messages to the MyReceiver via a PendingIntent) - Since both alarms are sending messages to MyReceiver and their corresponding PendingIntents are initialized with PendingIntent.FLAG_UPDATE_CURRENT will the new alarm override the old one? (this is what I want to do, in case for some reason the alarm gets cancelled after device boot it should be restarted when the application starts).
In MyReceiver's onReceive() I will create a MyIntentService (this instance will make the webservice call and update the local database).
Is this a good solution? Any suggestions?
Thanks
Solution is fine...Actually all the AlarmManager instances get cleared when device turned off and rebooted.
The simple way is that...
First create AlarmManager when application started.
Second in onReceive of BOOT_COMPLETED BroadcastReceiver.
Its enough, PendingIntent.FLAG_UPDATE_CURRENT will make sure of having only one activated alarm at a time.
In this way, alarm registered when your application started. There will be no issue if its already registered via BOOT_COMPLETED. Activated alarm will deactivated when you turn off your device, but BroadcastReceiver to BOOT_COMPLETED will take care of registration new alarm at next boot.
If you decide that this answers your question, please mark it as "accepted". This will raise both your and my reputation score.
Also you need to review your interval to use network, it might be very resource consuming for device and user. One policy might be to have longer period of interval and check for update when user starts your app (this might not be user friendly but can save many system resources and battery power as well). Try to find some better policy according to your needs.
Using FLAG_UPDATE_CURRENT in that manner will override the existing PendingIntent if one exists. I'm not positive but I believe that as soon as you get into onReceive, the PendingIntent is consumed so it's no longer there to be overridden. In either case, it sounds like this is the functionality you are looking for and yes it's a good way to solve this kind of problem. My only other suggestion would be if the 10 minute interval timing is not absolutely critical then use one of the INTERVAL_ schedules (INTERVAL_FIFTEEN_MINUTES for example) in your AlarmManager to help conserve battery life; basically it lets allows all apps that run on intervals to "batch" their work together and wake the device up less frequently.
Is there a time listener in Android?
I have a service that implements a location Listener. When there is no GPS lock, eg in a subway, I would like to send a notification based on time.
eg. If the train arrives at station A at 12:30.
If the current clock is 12:30, I would like to send a notification to the user.
The problem is that I didn't find anywhere a method for "onTimeChanged". Is there any way to achieve that?
I know about the System.currentTimeMillis()) but where do I put it to check every second?
You can use TimerTask class http://developer.android.com/reference/java/util/TimerTask.html which would help you to schedule new Task after some time interval.
You'll be able to achieve this using AlarmManager
This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running.
First time I have tried to implement either of these and I am unsure which to use.
I want my application to create a time frame, e.g. 2/3/12 to 7/3/12. Multiple time frames such as this can be created. A different intervals (e.g. every 4 hours) I would like my application to preform some actions for each time frame. This needs to be done in the background.
I have first tried to implement this with a Service, but am having performing all the actions for each of the time frames concurrently. After reading the android blog "Multitasking the android way" I think that perhaps BroadcastReceivers are better.
Please advise
Please see my answer about using the AlarmManager - Running task periodicaly(once a day/once a week)
If you are only running a process at a set time rather than constantly (e.g. monitoring audio levels) then you are going to ask a service to sit there 90% of the time and do nothing except waste battery power. The AlarmManager solves this problem as it notifies the broadcast receiver to execute at the given times.
Edit: Also bear in mind that after phone restart all alarms are removed so you will need to register a broadcast receiver to be notified of the device boot-up so you can re-register any Alarms that are needed.
You should probably be using the AlarmManager and a IntentService.
The AlarmManager will kick of your IntentService at specified intervals. You can kick off the IntentService for each set of actions.