Specify time delay for sending Notification in Android Studio?

Viewed 917

I have setup Notification Channels in Android Studio for sending my notifications.

So far, I can send a notification when I click a button.

However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.

I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.

Here is my code:

public class MyNotificationPublisher extends Application {

    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";

    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }

    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(
                    CHANNEL_1_ID,
                    "Channel 1",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(
                    CHANNEL_2_ID,
                    "Channel 2",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}
public class EmailActivity extends AppCompatActivity {
    private Button btnSend;
    private NotificationManagerCompat notificationManager;
    private long tenSeconds = 10000L;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_email);

        notificationManager = NotificationManagerCompat.from(this);

        btnSend = findViewById(R.id.button_send);
    }

    public void sendOnChannel1(View v) {


        Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Hi")
                .setContentText("Test")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .build();

        notificationManager.notify(1, notification);
    }

}
2 Answers

You can just schedule the notifications to be sent :-

Use the following method :


public void scheduleNotification(Context context, long delay, int notificationId)
 {
//delay is after how much time(in millis) from current time you want to schedule the notification
 NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); 

Intent intent = new Intent(context, YourActivity.class);

 PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);

 builder.setContentIntent(activity); Notification notification = builder.build();

 Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
 notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
 notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification); 

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

 long futureInMillis = SystemClock.elapsedRealtime() + delay; 

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent); 

} 

Then, the receiver class:


public class MyNotificationPublisher extends BroadcastReceiver {

 public static String NOTIFICATION_ID = "notification_id"; 

public static String NOTIFICATION = "notification";

 @Override 
public void onReceive(final Context context, Intent intent)
 {
 NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

 Notification notification = intent.getParcelableExtra(NOTIFICATION);

 int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
 notificationManager.notify(notificationId, notification); 
}
 } 

Then, call scheduleNotification with the appropriate arguments.

Use a handler to delay the execution of notification sending code

Update your code like that

 public void sendOnChannel1(View v) {


        Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Hi")
                .setContentText("Test")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .build();

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
        notificationManager.notify(1, notification);
        }
    }, 20000);

    }
Related