为什么 Handler 没有按预期触发警报?
我需要我的应用程序在用户按下按钮后指定的时间内触发警报。文档使它看起来像 Handler 就是我所需要的,并且用法似乎是脑死亡的。
然而,我发现尽管使用了 postDelayed,我的例程仍然立即运行。我知道我错过了一些明显的东西,但我就是看不到它。为什么下面的代码让手机立即振动而不是等待一分钟?
...
final Button button = (Button) findViewById(R.id.btnRun);
final Handler handler = new Handler();
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
...
handler.postDelayed(Vibrate(), 60000);
}
});
...
private Runnable Vibrate() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(300);
return null;
}
I need my app to trigger an alert a specified amount of time after a user presses a button. The documentation makes it look like Handler is what I need, and usage appears to be brain dead.
However, I'm finding that despite using postDelayed, my routine is running immediately. I know I'm missing something obvious, but I just can't see it. Why does the code below make the phone vibrate the immediately rather than waiting a minute?
...
final Button button = (Button) findViewById(R.id.btnRun);
final Handler handler = new Handler();
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
...
handler.postDelayed(Vibrate(), 60000);
}
});
...
private Runnable Vibrate() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(300);
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是因为你的做法不对。只需查看流程即可:
handler.postDelayed(Vibrate(), 60000) 将立即调用 Vibrate() 方法,然后运行振动器内容。事实上,
Vibrate()
返回 null?您认为处理程序将如何处理空引用?您很幸运,它没有抛出NullPointerException
。关于如何正确实现处理程序的例子太多了......只需在谷歌上多挖掘一点即可。然后:
That's because you are doing it the wrong way. Just see the flow:
handler.postDelayed(Vibrate(), 60000)
will call theVibrate()
method immediately, and then it runs the vibrator stuff. In factVibrate()
returns null? What do you think that the handler will do with a null reference? You are lucky that it does not throw aNullPointerException
. There are too many examples of how to correctly implement a handler... just dig a little bit more on google.Then:
您需要为 Vibrate 编写一个
run()
方法:You need to write a
run()
method for Vibrate:对您来说最简单的方法是使用 Runnable 的匿名对象,
final Button button = (Button) findViewById(R.id.btnRun);
最终处理程序处理程序=新处理程序();
振动器 v = (振动器) getSystemService(Context.VIBRATOR_SERVICE);
按钮.setOnClickListener(new OnClickListener() {
...
The simplest way for you would be to use anonymous object of Runnable,
final Button button = (Button) findViewById(R.id.btnRun);
final Handler handler = new Handler();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
button.setOnClickListener(new OnClickListener() {
...