在我的应用中,我有timer
。但是当我在toast
内部timer
时,应用程序崩溃了。但是,当我只增加一个变量时,计时器就可以工作。
这是我的代码:
package com.dev.moritz.colora;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class gameActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game);
startGame();
}
public void startGame() {
Timer ballMovement = new Timer();
ballMovement.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Round", Toast.LENGTH_SHORT).show();
}
}, 0, 5000);
}
}
我希望有人能帮助我。 Moritz的
答案 0 :(得分:1)
试试这个:
public void startGame() {
Timer ballMovement = new Timer();
ballMovement.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Round", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5000);
}
答案 1 :(得分:1)
<强>原因:强> 在非UI线程上运行的任何任务都无法与UI交互。
因此,当您想要从Timer Task更新UI时,一种方法是使用来自runOnUiThread()
类的Activity
,将这段代码放在TimerTask's
中} run()
方法:
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(gameActivity.this, "Round", Toast.LENGTH_SHORT).show();
}
});
它将按预期工作。
答案 2 :(得分:0)
使用 runOnUiThread ,
尝试以下代码runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Round", Toast.LENGTH_SHORT).show();
}
});
答案 3 :(得分:0)
Exception: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
这是您可以尝试的选项。
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
private Handler updateUI = new Handler() {
@Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
Toast.makeText(MainActivity.this, "142", Toast.LENGTH_SHORT).show();
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) { e.printStackTrace(); }
}
}, 0, 5000); // time in milliseconds
答案 4 :(得分:-2)
我试着在我的结束,这里工作正常:
您必须拥有RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
要克服上述问题,请将您的方法更改为:
public void startGame() {
Timer ballMovement = new Timer();
ballMovement.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main2Activity.this, "Round", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5000);
}