gpt4 book ai didi

安卓:倒数计时器

转载 作者:行者123 更新时间:2023-11-29 00:11:05 26 4
gpt4 key购买 nike

我正在尝试在经过一定时间后发送一条消息(如代码中所示的 SMS)。但我认为 CountDownTimer 无法正常工作,因为它会在显示通知后立即发送第一条消息。

下面是代码

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);

mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity2Activity.class);

Notification notification = new Notification(R.mipmap.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

mManager.notify(0, notification);

CountDownTimer waitTimer;
waitTimer = new CountDownTimer(180000, 60000) {

public void onTick(long millisUntilFinished) {
sendmessage();
}

public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();


}

那么我怎样才能让计时器正常等待呢?因为正如我所说,它会在调用通知后立即发送第一条消息。

注意:如果用户点击通知,它会打开一个应该终止 CountDownTimer 的 Activity ,但我无法实现。怎么做到的?我找不到任何相关信息。

最佳答案

观察 CountDownTimer 发现第一次 onTick() 在调用 onStart() 之后立即被调用,之后它在指定的时间之后被调用指定的间隔。

其次,传递给 180000 的第一个参数告诉计时器在 180000 毫秒后调用 onFinish() 并在 60000 毫秒后调用 onTick()立即开始之间。如果你想限制它不在第一次发送消息,你可以像这样做这个简单的检查:

CountDownTimer waitTimer;
waitTimer = new CountDownTimer(180000, 60000) {
boolean firstTime = true;
public void onTick(long millisUntilFinished) {
if (firstTime) {
firstTime = false;
return;
}

sendmessage();
}
}

public void onFinish() {
//After 180000 milliseconds finish current
//if you would like to execute something when time finishes
}
}.start();

您也可以使用 TimerTask 来执行相同的操作:

Timer waitingTimer = new Timer();
waitingTimer.schedule(new TimerTask() {
@Override
public void run() {
sendMessage();
// Add a base condition here to cancel the task if needed..
}
}, 60000, 180000);

关于安卓:倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com