Loizos Aristeidis
Loizos Aristeidis

Reputation: 159

Android Studio - How to Schedule a Notification?

I have created a sample notification for a project I am currently working on, using this code in the onCreate method of my Main Activity. I have also got a TimePicker Fragment class, which as the name suggests, opens up a time picker dialogue which allows the user to set a specific time of day. Then, the hour and minutes are stored in DataSite.class, which holds a number of get and set methods. Below is the code for TimePicker.class:

public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        DataSite ds = new DataSite();
        ds.setHour(hourOfDay);
        ds.setMinute(minute);
    }
}

In short, I would like to schedule the createNotificationChannel(); method call on the Main Activity, according to the hour and minutes the user has selected. As I said, the time information is stored in DataSite.

I have gotten the time picker working, and the notification shows as expected. All that I need now is a way to combine these two functionalities. As far as I can tell from other forum posts, I will have to use the Alarm Manager, but nothing I have read elsewhere works for me.

Edit: I have attempted to utilize the AlarmManager. Below you can see the full code I currently have so far:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial_screen);
        .
        .
        .
        .
        .
        Intent intent = new Intent(this, InitialScreen.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "reflectnotification")
                .setSmallIcon(R.drawable.app_icon_background)
                .setContentTitle("Reflect Reminder")
                .setContentText("Time to Reflect on your selected Goal!")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Time to Reflect on your selected Goal!"))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        createNotificationChannel();
//        notificationManager.notify(200, builder.build());

        hour = ((DataSite)getApplication()).getHour();
        minute = ((DataSite)getApplication()).getMinute();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);

        Toast.makeText(getApplicationContext(),"Picked time: "+ hour +":"+minute, Toast.LENGTH_LONG).show();

        alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent intent2 = new Intent(getApplicationContext(), InitialScreen.class);
        alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 200, intent2, 0);

        alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
    }
    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Reflect Reminder";
            String description = "Time to Reflect on your selected Goal!";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("reflectnotification", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

Upvotes: 1

Views: 9823

Answers (2)

Zaman Rajpoot
Zaman Rajpoot

Reputation: 523

Okay After too much research and fighting with this finally I did it Note: this is suitable for Android O+ Versions In Activity Class

button.setOnClickListener(view -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Calendar calendar = Calendar.getInstance();
            //10 is for how many seconds from now you want to schedule also you can create a custom instance of Callender to set on exact time
            calendar.add(Calendar.SECOND, 10);
            //function for Creating [Notification Channel][1]
            createNotificationChannel();
            //function for scheduling the notification
            scheduleNotification(calendar);
        }
    });

code for createNotificationChannel()

@RequiresApi(api = Build.VERSION_CODES.O)
public void createNotificationChannel() {
    String id = "channelID";
    String name = "Daily Alerts";
    String des = "Channel Description A Brief";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel channel = new NotificationChannel(id, name, importance);
    channel.setDescription(des);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
}

code for scheduleNotification(Calender calendar);

@RequiresApi(api = Build.VERSION_CODES.M)
public void scheduleNotification(Calendar calendar) {
    Intent intent = new Intent(getApplicationContext(), Notification.class);
    intent.putExtra("titleExtra", "Dynamic Title");
    intent.putExtra("textExtra", "Dynamic Text Body");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    Toast.makeText(getApplicationContext(), "Scheduled ", Toast.LENGTH_LONG).show();
}

Notification.kt

    class Notification : BroadcastReceiver() 
{
    override fun onReceive(context: Context, intent: Intent) {
        message = intent.getStringExtra("textExtra").toString()
        title = intent.getStringExtra("titleExtra").toString()
        val notification =
            NotificationCompat.Builder(context, channelID).setSmallIcon(R.drawable.notification)
                .setContentText(message).setContentTitle(title).build()
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(notificationId, notification)
    }
}

Upvotes: 1

E.M.
E.M.

Reputation: 4547

If there is an exact time that the notification needs to be sent, you will want to use AlarmManager. See https://developer.android.com/training/scheduling/alarms

The docs describe when to use AlarmManager vs. other APIs: https://developer.android.com/guide/background#alarms

Upvotes: 1

Related Questions