[英]Display Alert Dialog when Activity onPause()
I am trying to show an alert dialog when a countdown timer finishes and the activity is sent in the background via the onPause()
method. 我试图在倒数计时器结束并且通过
onPause()
方法在后台发送活动时显示警报对话框。
I did some research but couldn't find something to fit my needs. 我做了一些研究,但找不到适合我需要的东西。
I tried to achieve this by using a handler: 我试图通过使用处理程序来实现这一点:
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int aResponse = msg.getData().getInt("message");
if (aResponse == DISPLAY_DLG) {
showStopAlarmDialog();
}
}
};
And in the timer's onFinish()
method 在计时器的
onFinish()
方法中
Message msgObj = myHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("message", DISPLAY_DLG);
msgObj.setData(b);
myHandler.sendMessage(msgObj);
However, this still only works when the activity is in the front. 但是,这仅在活动处于最前面时才起作用。
I would recommend using the AlarmManager for this task. 我建议为该任务使用AlarmManager 。 Otherwise you have to be aware of handling a wake lock so the device doesn't goes to sleep, and if the time to elapse is too long then you will hit unnecessary battery drain.
否则,您必须知道要处理唤醒锁,以使设备不会进入睡眠状态;如果经过的时间过长,则会浪费不必要的电池。
Using the AlarmManager to fire an Intent and receive it in your app is the way that has work the better for me. 使用AlarmManager触发Intent并在您的应用程序中接收它对我来说是更好的方法。 Be sure to set the alarm when the activity goes to onPause() and unset the alarm when onResume() .
请确保在活动进入onPause()时设置警报,而在onResume()时取消设置警报。 You can also check if launching an Activity with Theme.Dialog is gonna suit better to your needs, 'cause if you lose the activity Context you won't be able to display a regular dialog.
您还可以检查是否启动带有Theme.Dialog的Activity是否更适合您的需求,因为如果丢失Activity Context,将无法显示常规对话框。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.