我最近收到了一个正在工作的应用程序的推送通知。唯一的问题是通知会立即到来。但我需要10分钟后再来。下面是我的代码,我如何使它在特定时间后出现?
public void onClick(View v) {
Intent i = new Intent(new Intent(Settings.this, Start.class));
startActivity(i);
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent, 0);
Notification noti = new Notification.Builder(Settings.this)
.setTicker("TickerTitle")
.setContentTitle("Price-Tracker")
.setContentText("ContentText")
.setSmallIcon(R.mipmap.pw)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
例如,我尝试将nm.notify(0, noti);
更改为nm.notify(10, noti);
,但它不起作用
不要使用thread.sleep,这是一个糟糕的解决方案。睡眠正在使用阻塞线程,而您可以在等待时继续其他作业。。。最好使用延迟后的处理程序或AlarmManager来处理您的等待时间。
您必须创建一个新的Thread
,设置睡眠10分钟,然后推送通知
public void onClick(View v) {
Intent i = new Intent(Settings.this, Start.class);
startActivity(i);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 10 minutes * 60000 milliseconds(1 minute)
Thread.sleep(10 * 60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent, 0);
Notification noti = new Notification.Builder(Settings.this)
.setTicker("TickerTitle")
.setContentTitle("Price-Tracker")
.setContentText("ContentText")
.setSmallIcon(R.mipmap.pw)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
}
}).start();
}
另外,将nm.notify(0, noti);
更改为nm.notify(10, noti);
也没有任何作用,因为0
是将显示的通知,也是第一个
您可以使用android.os.Handler来执行有延迟的作业。
long DELAY = 10 * 60 * 1000; // 10 minutes
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//the job you want to be executed after DELAY milliseconds
}
}, DELAY);
如果这个答案有帮助,请单击类似按钮下的复选标记来表示。
添加以下
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
nm.notify(0, noti);
}
});
}
},600000);
10分钟=60000毫秒
使用runOnUiThread从另一个或工作线程更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
nm.notify(0, noti);
}
});