apchar apchar - 1 month ago 14
Android Question

android thread only runs once

I just wanted to test

Log.i()
and look at the console in android studio. In the code below
onResume
should start the
thread
and
run()
should write an endless stream of "dings" with the tag "run" in the monitor. But the run method apparently only gets called once. Why?

public class MainActivity extends Activity implements Runnable {
Thread gameThread = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("onCreate","getting started");
}

public void run() {
Log.i("run","ding");
}

@Override
public void onResume() {
super.onResume();
gameThread = new Thread(this);
gameThread.start();
}
}

Answer

You're missing the notion of what threading really does. It allows you to run a unit of work asynchronously. So, all the same normal rules apply. The reason it only runs once, is because the thread exits after run() returns. So just like any other method, you should put something like

while(true)
{
    Log.i("run","ding");
}

inside of run(). Ideally you would actually check some condition so that you can exit the thread as needed.

Finally, it is probably a bad idea to have your MainActivity implement Runnable. Typically it is good style to have a thread implemented by its own class, for example DingThread implements Runnable.