Android background service for calling a webservice every 5 minutes - android

I need a background service for my android app that every 5 minutes calls a webservice and stores the received data in a database . The webservice is already fully functional and every 5 minutes has new data available. And also how can I make this service make the webcalls at precise times, I need it to make the calls at certain minutes and seconds.
For example it has to make the calls at 12:05:05 and then at 12:10:05 and after that at 12:15:05 and so on. The reason for this is because the webservice has new data at precise times and I want to get it as soon as it is available. What couldbe the best solution for this problem?

You could use the AlarmManager to start an IntentService which calls the webservice.
Here is a good explanation of this technique.

you have to used below code for calling method every 5 minutes.
// some time when u want to run
Date when = new Date(System.currentTimeMillis());
try{
Intent someIntent = new Intent(someContext,MyReceiver.class); // intent to be launched
// note this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id, optional
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT); // PendintIntent flag
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}catch(Exception e){
e.printStackTrace();
}

You can learn the fundamentals of services from here. And then learn about REST web services from here.
Also learn about Databases in Android from here.

Related

Loaders vs. Asyncctask vs. others

In my app, I need to update the database with some data from the server. The data need not be shown to the user immediately. It is also fine if the new data is shown to the user the next time he uses the app. There is no UI component that needs to be updated now because of this operation. So, I just need to fetch some data from the server in the background, when the app is running.
currently I am using an Asynctask in an activity. But it does not handle configuration changes well. So, I was reading up a bit and came across a few options:
Using Loaders
Using Fragments
Using Asynctask in a fragment
Using static Asynctask
I am a bit new to this and am quite confused what would be the best implementation method for my requirement. Kindly suggest
Just in case it might help someone. What I have done to fix this is:
Use an alarmmanager to setrepeating alarm that would invoke a service at specific intervals to fetch the data. Something like the code below is called the first time the app runs.
Intent i = new Intent(WordListActivity.this, NewData.class);
PendingIntent pint = PendingIntent.getService(
WordListActivity.this, 0, i, 0);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC, cal.getTimeInMillis() + 10000,
gap, pint);

Schedule an alarm's array in Android

I am making a personal organizer. From the calendar the user can choose the day and then can make a date with a specific hour. At this date and hour the application should show an other activity, which is the notification. User can make just one note for day. So the pk of each note is YYYYMMDD.
So, I wants to know that what I've done is right or not.
I've a service which is started with application. The onStartCommand of the service checks if in the current date there is a note in the db and, if there is, he calls the Activity Notification. I've a runnable thread which is looping each minute and it update the date if the service, because the date of the onStartCommand is static. If the date getted by the runnable is equal to onStartCommand's date then keep cycling, else I start the service again with:
Intent myIntent = new Intent(Receiver.this, NotificaSuoneria.class);
startActivity(myIntent);
In this way I haven't any troubles, but I want to know if the runnable thread could be killed by android, because if killed I can't check the alarms of the others days.
And, when I restart the service each time update the date, the old runnable thread will be killed or will were a lot of threads?
P.S.
I don't use the AlarmManager for schedule the alarm. If the datenow have some engagement with alarms I calculate the time left and sleep for this time, then I'll start the notification activity. Sorry for my poor english.
You should use AlarmManager for this with a loop like following edited
try {
cntxt = createPackageContext("your.app.package",CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
// handle exception here
e.printStackTrace();
}
Intent myIntent = new Intent(cntxt , yourreciever.class);
PendingIntent pi;
AlarmManager alarmManager;
for(int i=0;i<=timesinday;i++)
{
pi=PendingIntent.getBroadcast(cntxt, i,myIntent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, currentcal.getTimeInMillis(),pi);
}
Do not forget to add NotificaSuoneria in Android Menifest as a Reciever. If you you want alarm to goes off every day you should use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,todaycal.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
#Meesta I am editing the answer you do not have to mention activity here Intent myIntent = new Intent(Receiver.this, here.class); here will be the reciever class from wher you can start your activity also see http://androidword.blogspot.in/2010/10/how-to-use-broadcast-receiver.html and try to add flag_new_activitywhen starting the activity from broadcast reciever

Android and checking for new data per hour

Im creating a news-like app and I want to know is is possible to start app (ex : 1 time per 1h) to check if new data is available. You know what im talking about, I think. App should start from nowhere, check and finish().
Is this possible? I know that widgets can do it but normal activity or something like this?
Please, help.
Damian.
Yes, It is possible to use an "Alarm Service" in android, and use it to perform some work, at specific intervals.
Here is the link to Alarm Service documentation:
http://developer.android.com/reference/android/app/AlarmManager.html
Here is a sample code which uses Alarm Service
/**
* Method to start background service for server refresh and other tasks.
*/
public void startMyService()
{
//Start Service service to handle data refresh
Intent serviceIntent = new Intent(this, MyCommunicationService.class);
//Schedule additional service calls using alarm manager.
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(this, 0, serviceIntent, 0);
//Retrieve time interval from settings (a good practice to let users set the interval).
MyPreferenceManager prefManager = new MyPreferenceManager(this);
alarmManager.cancel(pi);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), prefManager.getDataRefreshTime()*1000 , pi);
}
Note that we are multiplying with 1000, because the parameter for setRepeating() method is in milliseconds.

How to set a timed event which will keep running even if the application is stopped

I need to have a process run whenever the end-user clicks on a Submit button. The application needs to try to process the data on the screen every X minutes, Y times, even if the the application is down. So, it will need to attempt to do some processing until one of the following occurs:
1) The processing is successful for the data that was submitted
2) The processing has been retried Y times and still never succeeded
3) The application is terminated by the OS or the phone is turned off.
If the end-user's phone is still on but the application has stopped,
what's the correct interface to use to accomplish this?
If I use Handler/Runnable, that only works as long as the application stays active.
AlarmManager looks like it's used when you want processing to run at a specific time.
Any suggestions will be greatly appreciated!
I use this method to set an alarm.
private void setAlarm(){
Context context = getApplicationContext();
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
myCal = Calendar.getInstance();
myCal.setTimeInMillis(myPrefs.getLong("time", 0));
mgr.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pi);
Log.i(myTag, "alarm set for " + myCal.getTime().toLocaleString());
Toast.makeText(getApplicationContext(),"Alarm set for " + myCal.getTime().toLocaleString(), Toast.LENGTH_LONG).show();
}
inside my onAlarmReciever onRecieve method is this:
Intent i = new Intent(context, AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
So basically when the intent fires it starts the AlarmActivity. Inside that activity you could have it try what ever you are doing and if it fails call the setAlarm() again
You have two options: a Service, or set up an alarm with AlarmManager. Which one you pick will depend mostly how often do you want to retry. A minute? Use a service. An hour? A day? set up an alarm so you don't waste the phone resources keeping the service alive.
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/reference/android/app/AlarmManager.html
Write an Android Service

pendingintent on alarms for android

When setting a service to go off at particular time, I use the AlarmManager system service.
Everything goes off without a problem, service is called and actions take place.
When the alarm time is reached, the service starts, and at this point I get the system time (System.currentTimeMillis()). I'm guessing this wont be the actual time the service start. Is there a way to get the time that was set for this PendingIntent?
ie
Set alarm for 9am.
DoStuffService starts at 9am.
DoStuffService knows it was supposed to start at 9am, and uses this value for future functions.
When you create an intent for your alarm, you could put extra data, including time of the alarm, into it like this:
Intent intent = new Intent("action name");
//put extra data into the intent:
intent.putExtra("alarm_time_hours", hours);
intent.putExtra("alarm_time_minutes", minutes);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
Then in your receiver or service you need to get this extra data from received intent. Use something like this:
Bundle bundle = intent.getExtras();
if(bundle.containsKey("alarm_time_hours")) {
int hours = bundle.getInt("alarm_time_hours");
}
if(bundle.containsKey("alarm_time_minutes")) {
int minutes = bundle.getInt("alarm_time_minutes");
}
Is there a way to get the time that was set for this PendingIntent?
No, sorry.
However, it should not be terribly difficult for you to determine it yourself. Following your example, if your service reports that it is now 09:00:02.36, you should be able to round down to determine that this is the 9am alarm.

Categories

Resources