As for every Android-dummy, also I run into the FATAL EXCEPTION
java.lang.IllegalThreadStateException: Thread already started
Scrolling forums and questions, I have seen that a Thread cannot be started twice. I have seen answers like these:
"It's not a good Idea to start a Thread more than once."
"A Thread can be called just one time."
But nobody says WHY a Thread can be called just once. It sounds so weird to me that there is an Android function that is born to be called only one time.
Why a Thread can be called just once?
I am developing an App in which I have to call an animation every time I tap the screen. I thought that a Thread could be the most suitable tool for me. Am I wrong?
UPDATE
Maybe the question is not clear.
I am not asking why a Thread cannot be restarted while it is alive.
I am asking why a Thread that I have run but now is finished (so it is not alive) cannot be called a second time.
This is my code fully simplified. The Thread is called the first time at onCreate
and the second time at onClick
, so when I tap the image.
At the second call, I can see from Android Monitor
that the Thread is not Alive, though it not starts anyway.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
chiamaDatabase();
RESET.start();
ImageView image = (ImageView) findViewById(R.id.imageView2);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!RESET.isAlive()) {
RESET.start();
}
}
});
}
public Thread RESET = new Thread() {
public void run() {
final ImageView image = (ImageView) findViewById(R.id.imageView2);
Random random = new Random();
int n = random.nextInt(2);
image.setX(320+n);
image.setY(400+n);
}
};