简体   繁体   中英

Scheduling notifications for the future in Oreo

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!

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 );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM