gpt4 book ai didi

java - Android - 创建同步计时器

转载 作者:太空宇宙 更新时间:2023-11-04 13:36:41 24 4
gpt4 key购买 nike

我知道计时器的工作原理是让线程 hibernate x 时间,但我想知道是否有某种计时器不在 UI 线程之外的线程上运行。我考虑过使用一个循环来不断比较系统时间(以毫秒为单位),但我想将其用作最后的手段,因为它似乎效率不高。

编辑:

堆栈跟踪:

07-25 14:38:38.037  22108-22124/com.example.myapp E/ViewRootImpl﹕ com.example.myapp.Main : Only the original thread that created a view hierarchy can touch its views.
java.lang.RuntimeException
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6355)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:929)
at android.view.ViewGroup.invalidateChildFast(ViewGroup.java:4466)
at android.view.View.invalidateViewProperty(View.java:11112)
at android.view.View.setTranslationY(View.java:10472)
at android.view.View.setY(View.java:10400)
at com.example.myapp.Player.update(Player.java:29)
at com.example.myapp.Main.update(Main.java:70)
at com.example.myapp.Main.access$000(Main.java:15)
at com.example.myapp.Main$1.run(Main.java:33)
at java.util.Timer$TimerImpl.run(Timer.java:284)

相关代码:

if (!onGround){

playerVisual.setY(playerVisual.getY() + this.gravity);

}

if (playerVisual.getY() >= this.main.getDevice().getHeight() - 10){
this.onGround = true;
}
else {
this.onGround = false;
}

如果您想知道的话,playerVisual 是一个 ImageView。

最佳答案

这是一个基于AsyncTask的解决方案:

class AsyncTimer extends AsyncTask<Void, Void, Void>
{
boolean alive = true;
long startMS;
long intervalMS;
MainActivity activity;

public AsyncTimer(long startMS, long intervalMS, MainActivity activity)
{
this.startMS = startMS;
this.intervalMS = intervalMS;
this.activity = activity;
}

protected Void doInBackground(Void... params)
{
try
{
Thread.sleep(startMS);
}
catch (Exception e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}

while (alive)
{
try
{
alive = activity.updateUI();
Thread.sleep(intervalMS);
}
catch (Exception e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}

return null;
}
}

在MainActivity中使用它:

    @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
new AsyncTimer(0, 1000, this).execute();
}

public boolean updateUI()
{
Log.d("Timer", "tick");
...
return true;
}

关于java - Android - 创建同步计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31627161/

24 4 0
文章推荐: php - 这种形式安全吗?
文章推荐: java - 属性继承?
文章推荐: java - jSTL中循环内的方法
文章推荐: php - 如何在不使用 strip_tags 的情况下从变量中删除
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com