在奥利奥计划未来的通知

时间:2018-06-19 14:12:34

标签: android notifications android-8.0-oreo

我正在使用Android Oreo的新通知系统。我想在将来安排通知。我制作了一个测试程序,应该在5秒钟后发出通知。而是,它立即显示通知。这是我的代码:

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

谢谢!

2 个答案:

答案 0 :(得分:0)

使用处理程序及其postDelayed方法按时间间隔发出通知

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

    @Override
    public void run() {
        //call your method here
        handler.postDelayed( this, 60 * 1000 );
    }
}, 60 * 1000 );

答案 1 :(得分:0)

恐怕您误解了setWhen函数的作用。使用此功能,您可以更改通知中显示的时间戳。如果您不知道我在说什么,请给它几个小时前的时间戳。

如果您想将来安排通知,则必须安排警报或将来的通知,并在触发警报时发送通知。如果您今天要在生产环境中使用此功能,我建议您使用android-job;如果您只是想尝试一下,建议使用新的WorkManager。 Evernote宣布,当WorkManager超出Alpha版本且稳定时,android-job将在未来的某个时间过时。

相关问题