Android 中的锁屏可加快游戏速度
我正在使用发布延迟可运行的处理程序来更新我的游戏。
public class Example implements Runnable
{
Handler handler;
public Example()
{
handler = new Handler();
handler.postDelayed(this,10);
}
public void run()
{
handler.postDelayed(this,10);
}
}
每当我按下锁屏按钮然后恢复游戏时,它的运行速度都比预期的要快得多。每次我锁定屏幕并恢复时,它运行得越来越快。但是,如果我重新启动活动或完成然后重新打开活动,它会再次以正常速度运行。请帮忙。 提前致谢。
I'm updating my game using a Handler posting a delayed Runnable.
public class Example implements Runnable
{
Handler handler;
public Example()
{
handler = new Handler();
handler.postDelayed(this,10);
}
public void run()
{
handler.postDelayed(this,10);
}
}
Whenever I press the lock screen button and then resume the game, it runs much faster than it is supposed to. Every time I lock the screen and resume, it runs faster and faster. However, if I restart the activity or finish and then re-open the activity, it runs at normal speed again. Help please.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎发生的情况是,每次您锁定屏幕然后恢复屏幕时,都会在您已经使运行加倍的
Runnable
之上创建另一个Runnable
,从而使线程继续运行每次都越来越快,当你锁定屏幕时,你需要以某种方式暂停你的线程,比如 thread.sleep() 或类似的东西,这样当你恢复时,你就不会重新创建一个新的 Runnable< /code> 而只是从你在线程中停止的地方。如果您在
onCreate
方法中创建一个新的Runnable
。每当手机旋转或手机恢复等时都会调用它,这就是您可能遇到此问题的原因。在您finish()
您的 Activity 或关闭您的应用程序后不会发生这种情况的原因是,当您重新启动应用程序时,Runnable
将被创建一次,直到您开始锁定手机并再次恢复等。您可能还想查看可用于帮助处理线程的内部类:
这可能有助于处理必须暂停/重新启动/恢复或其他更好的线程。更多信息在这里: http://developer.android.com/reference/android/os /AsyncTask.html
不知道它在游戏中如何工作,但没有尝试过。
祝你好运,希望这有帮助。
What seems to be happening is every time you lock your screen and then resume it is making another
Runnable
on top of theRunnable
you already have doubling your run thus making the thread go faster and faster everytime, you need to somehow pause your thread something likethread.sleep()
or something similar when you lock your screen so when you resume you aren't recreating a newRunnable
and instead just starting from where you left off in your thread.If you are making a new
Runnable
in anonCreate
method. It is going to get called anytime the phone is rotated, or when the phone resumes etc. and thus is why you are probably having this issue. The reason it doesn't happen after youfinish()
your activity or close your app is because when you restart the app, thatRunnable
is going to get created once, until you start locking the phone and resuming again etc.you may also want to look at an inner class you can use to help handle your threads:
This might help handle threads that have to be paused/restarted/resumed or whatever a little better. More info here: http://developer.android.com/reference/android/os/AsyncTask.html
Dunno how it would work in a game though, didn't play around with that.
Good Luck, hope this helps.