Background Process Timer On Android
Solution 1:
Ok, first of all, I really don't know if I got your question quite right. But I think you want a timer that's being executed every 30 seconds ,if i'm not mistaken. If so, do as following:
Note: 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. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
Example:
in your onClick()
register your timer:
intrepeatTime=30; //Repeat alarm time in secondsAlarmManagerprocessTimer= (AlarmManager)getSystemService(ALARM_SERVICE);
Intentintent=newIntent(this, processTimerReceiver.class);
PendingIntentpendingIntent= PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Repeat alarm every second
processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),repeatTime*1000, pendingIntent);
And your processTimerReceiver class:
//This is called every second (depends on repeatTime)publicclassprocessTimerReceiverextendsBroadcastReceiver{
@OverridepublicvoidonReceive(Context context, Intent intent) {
//Do something every 30 seconds
}
}
Don't forget to register your receiver in your Manifest.XML
<receiverandroid:name="processTimer" ><intent-filter><actionandroid:name="processTimerReceiver" ></action></intent-filter></receiver>
If you ever want to cancel the alarm: use this to do so:
//Cancel the alarmIntentintent=newIntent(this, processTimerReceiver.class);
PendingIntentpendingIntent= PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManageralarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Hope this helps you out.
PS: if this is not exactly what u want, please leave it in the comments, or if someone wants to edit this, please do so.
Solution 2:
Oh god, don't ever use AlarmManager for 30s timers. It's kind of an overkill and also put a significant drain on device resources (battery, CPU...).
Perhaps you could try using a real background Service instead of IntentService as IntentService tends to shut itself down when it runs out of work. Not sure if this is the case here, but it's worth a try.
Post a Comment for "Background Process Timer On Android"