Search code examples
androidbroadcastreceiver

BroadcastReceiver and AlarmManager not working with


I've been trying to fix this for hours but I still don't get it.

My code is very basic:

BroadcastReceiver

 public class TimerNotif extends BroadcastReceiver
 {

    @Override
    public void onReceive(Context context, Intent intent)
    {
        notificationStatus(context);
    }

    private void notificationStatus(Context context) {
        final NotificationManager mNotificationManager = (NotificationManager) 
                context.getSystemService(Context.NOTIFICATION_SERVICE);

        final int icon = R.drawable.ic_launcher;
        final Notification notification = new Notification(icon, "test", System.currentTimeMillis());
        final Intent notificationIntent = new Intent(context.getApplicationContext(), Main.class);
        final PendingIntent pIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, "ticker", "title", pIntent);
        mNotificationManager.notify(1, notification);
    }
}

Main activity

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Calendar cal = Calendar.getInstance();

    Intent intent = new Intent(Main.this, TimerNotif.class);
    PendingIntent pIntent = PendingIntent.getBroadcast(Main.this, 0, intent, 0);

    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);
}

And this into application tag in Manifest

<receiver android:name="TimerNotif"></receiver>

Nothing happens! The code into TimeNotif is not running, but why?


Solution

  • Should be:

    <receiver android:name=".TimerNotif"></receiver>
    

    Because ".TimerNotif" is a shortcut for full class name, if your class is in the root package of your application. Otherwise, it should be:

    <receiver android:name="your.package.name.TimerNotif"></receiver>