0

I'm using Android Oreo's new notification system. I want to schedule a notification in the future. I made a test program that is supposed to fire a notification 5 seconds later. Instead, it displays the notification immediately. Here is my code:

public class MainActivity extends AppCompatActivity {
    private NotificationManager manager;

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

        NotificationChannel notificationChannel = new NotificationChannel("default",
                "primary", NotificationManager.IMPORTANCE_DEFAULT);
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Notification notification = new Notification.Builder(getApplicationContext(), "default")
                        .setContentTitle("title")
                        .setContentText("body")
                        .setWhen(Calendar.getInstance().getTimeInMillis() + 5000)
                        .setSmallIcon(android.R.drawable.stat_notify_chat)
                        .setAutoCancel(true)
                        .build();
                manager.notify(123, notification);
            }
        });
    }
}

Thanks!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Brandon
  • 33
  • 1
  • 5

2 Answers2

0

Use a Handler and its postDelayed method to give the notification in time intervals

final Handler handler = new Handler()
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        //call your method here
        handler.postDelayed( this, 60 * 1000 );
    }
}, 60 * 1000 );
Hitesh Anshani
  • 1,499
  • 9
  • 19
0

I'm afraid you've misunderstood what the setWhen function does. With this function you can alter the timestamp that is displayed in the notification. If you don't know what I'm talking about give it a timestamp of a few hours ago.

If you want to schedule notifications in the future you'll have to schedule an alarm or something for the future and send the notification when the alarm is triggered. I would recommend using android-job if you need this functionality in production today or the new WorkManager if you're just trying things out. Evernote has announced android-job will become deprecated some time in the future when WorkManager is out of alpha and stable.

Community
  • 1
  • 1
Sander
  • 808
  • 6
  • 18