How do I periodically broadcast an event after user has installed my application.
I have implemented a broadcast receiver which will trigger a task onReceive. Now I need to periodically broadcast this event, so that the task will be executed periodically.
I know I need to use AlarmManager.
The code is somewhat like this.
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, 0, 5*1000, pendingIntent);
Q1) Where do I place this code if I do not have any Activity? Do I implement this as a service?
Q2) What should be the intent-filter be for my manifest in such a “self created event”?
PS: Actually my current broadcast receiver is waiting for the connectivity change event. The task is to periodically attempt/try to access the internet. But I cannot solely rely on connectivity change to trigger this task. That’s why I need a timer which will either fire this event or trigger the method in onReceive().
I know in this case my intent-filter will be “android.net.conn.CONNECTIVITY_CHANGE”
You need to implement an activity. Nothing of your application will run on Android 3.1+ until the user has launched your activity.
So, you run this code:
The first time the user runs your activity
On a reboot (via a
BOOT_COMPLETEDBroadcastReceiver)In the future when the user runs your activity, if you have determined that no broadcasts have gone out in too long, because the user force-stopped your application
Also, get rid of
getApplicationContext(), as you should not need it here.You do not need one, as your
Intentidentifies the component.