The following code I have in onCreate
for one of my Activity
classes. I am expecting a log output every second when I enter that activity, but nothing happens.
private void setupAlarm() {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this,AdhIntent.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pendingIntent);
}
private class AdhIntent extends BroadcastReceiver {
public AdhIntent() {
System.out.println("2014");
}
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("2014");
}
}
First, AdhIntent
needs to be a public
class. Otherwise, Android cannot create an instance of it.
Second, AdhIntent
needs to be registered in the manifest in a <receiver>
element. Otherwise, Android cannot send a broadcast to it via your PendingIntent
.
You also do not need getApplicationContext()
-- only use that when you know completely and precisely why you are using it.
Finally, using AlarmManager
to get control every second is not a particularly good use of AlarmManager
. At best, that's fine for book examples, or for lightweight testing. If you really need to get control somewhere every second, there are better solutions, assuming that getting control every second is actually a sensible choice.