Skip to content
Advertisement

Displaying notifications at a certain time with Android Studio

I’m pretty new to Android Studio and Java in general. I’m trying to build an app that, based on whether a checkbox is ticked in the app’s settings menu, will display a notification everyday at 8AM.

I’ve figured out how to display the notification, but not how to trigger it at 8AM. This is the current notification code:

    private void addNotification() {
        NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.cog)
                    .setContentTitle("Notifications Example")
                    .setContentText("This is a test notification");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
}

My questions are two:

  1. How do I make the notification trigger at 8AM every day?
  2. How do I make the app remember if the checkbox is ticked or not?

Any help appreciated 🙂

Advertisement

Answer

Welcome to Stack Overflow. 🙂

You can use the AlarmManager class to trigger a notification at a particular time. The Android developer website has a great section on how to use it: https://developer.android.com/training/scheduling/alarms#examples-of-real-time-clock-alarms

To help the app remember if the checkbox is checked, SharedPreferences should be enough. There’s another page on the Android developer website on how to use it: https://developer.android.com/training/data-storage/shared-preferences

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement