gpt4 book ai didi

Android 通知管理器在屏幕关闭时不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:10 25 4
gpt4 key购买 nike

我有一个倒计时计时器,当它关闭(到零)时,它会检查应用程序是否有焦点。如果没有,它会在通知栏中启动通知。当您单击通知时,会重新打开应用程序。现在所有这些都可以正常工作,但如果屏幕碰巧关闭,计时器会继续运行并且通知会在正确的时间可用,但在我重新打开屏幕之前不会真正振动或响铃。然后它会显示通知,就像在队列中等待一样。

我如何获取它以便通知管理器在屏幕关闭时真正提醒用户?

更新:如果我将定时器设置为 2 分钟,则通知还需要 2-3 分钟才能真正起作用。所以它确实有效,但它有很大的延迟!

代码:所以我在应用失去焦点时设置通知服务,当 MyCount1 完成时检查应用是否有焦点,如果没有则显示通知。当屏幕背光打开时,这一切都有效。一旦它熄灭,它就不可靠了。

@Override
public void onWindowFocusChanged(boolean hasFocus){
if(hasFocus == false){
mFocusFlag = false;

ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) getSystemService(ns);
icon = R.drawable.statusbar;
tickerText = "Check the timer!!!";
when = System.currentTimeMillis();
notification = new Notification(icon, tickerText, when);
context = getApplicationContext();
contentTitle = "Countdown Timer";
contentText = "Click to Check the Timer";
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationIntent = new Intent(this, StartTimer.class);
contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

}else{
mFocusFlag = true;
}

}

public class MyCount1 extends CountDownTimer {
public MyCount1(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
if(mFocusFlag == false){
mNotificationManager.notify(HELLO_ID, notification);
}else{
mVib.vibrate(1000);
}
}
public void onTick(long millisUntilFinished) {
if((millisUntilFinished/1000%60) < 10){
mTime.setText("1st Side = " + millisUntilFinished/60000 + ":0" + (millisUntilFinished / 1000)%60);
}else{
mTime.setText("1st Side = " + millisUntilFinished/60000 + ":" + (millisUntilFinished / 1000)%60);
}
}
}

最佳答案

Now all of this works fine but if the screen happens to go off, the timer keeps going and the notification is available at the right time but never actually vibrates or rings until i turn the screen back on. Then it displays the notification like it was waiting in a queue or something.

How do I get it so that the notification manager will actually alert the user when the screen is turned off?

当屏幕关闭时,CPU 将很快停止运行,除非有东西持有 WakeLock

这意味着两件事之一:

  1. 您了解所有这些并持有 WakeLock。从用户喜欢他们的设备的角度来看,这可能是也可能不是一个好主意(例如,良好的电池生命周期)。尽管如此,您可能需要保持更强大的 WakeLock,至少让屏幕保持暗淡。我没有尝试在 WakeLock 下引发 Notification,所以我不确定所有规则是什么。

  2. 您不了解所有这些,因此认为您的计时器正在计时,但实际上设备已经休眠并且 CPU 已关闭。当 CPU 再次打开时,您的计时器将立即关闭。

使用 AlarmManager 允许您执行唤醒设备的基于计时器的事件,同时不需要您的代码在内存中徘徊。我不知道你想在这里做什么(从你的描述来看似乎很奇怪),但是 AlarmManager 可能是值得研究的东西作为你的计时器的替代品。

关于Android 通知管理器在屏幕关闭时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4169558/

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