Search code examples
androidbroadcastreceiveralarmmanagerandroid-pendingintent

Cant get AlarmManager and broadcast working


No matter how I try, I cannot get the alarmManager and receiver to work - there seem to be SO many different ways to do it from what i've searched, but nothing seems to work.

I have in Manifest:

<receiver android:name="AlarmReceiver" />

I am using inner class for broadcastReceiver:

private class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("ALARM","TRIGGERED");
        Notification(filteredList.get(0).getTitle());
    }

}

I call function SetAlarm to start the manager:

private void SetAlarm(long time) {

    AlarmManager alarm_mgr = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
    //PendingIntent pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
    PendingIntent pi = PendingIntent.getBroadcast(this, 111, intent, PendingIntent.FLAG_UPDATE_CURRENT);


    Calendar calendar = Calendar.getInstance();
    alarm_mgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
    Log.d("ALARMSET", "Alarm " + calendar.getTime().toString());
}

As you can see, in the receiver I have a notification call - I won't post because I know this works, but there is also a log that is not working. For testing purposes I've set time to current time using the Calendar function. You can see the pendingIntent, i have tried both getService and getBroadcast, I can't figure out which I need, but neither works anyway.

I'm sure I'm missing something, i don't know what, and I can't seem to find any answers at Google.

Is the AlarmReceiver ok as an inner class ? I have put it there because I need access to my "filteredList" List object.

thx


Solution

  • No, actually the BroadcastReceiver needs to be public.Only then you can register it in manifest and access them. Place the AlarmReceiver code in a separate .java file. You will see the log inside the BroadcastReceiver.