When working with media players, it is strongly
advised to create a new Thread
for each Player
and not to reuse the Thread
. Media players by nature
can be slow to start and stop, and sometimes these delays can last
many seconds. Always use a fresh thread so that these long delays
have a minimised effect on other parts of your application. New media
players may need to be created in response to user input, for example
when the previous player is unresponsive or has not yet finished closing
down.
The best thread solution depends on game structure, but basically it is good to have separate threads for rendering and game logic to ensure smoothness.
Do not let a wrong timing drive the main loop of your application. For example, sensor ticks come in very slowly, much more slowly than the phone can repaint the screen.
There is also a danger that your threads do not give time for EDT and your game stops to handle input events. One solution is to make your thread to force-sleep one millisecond for EDT.
public void run() { long lastTime = 0; while (run) { long now = System.currentTimeMillis(); long delay = (1000 / MAX_RENDERING_FPS) + lastTime - now; if (delay < 1) { delay = 1; } // force-sleep at least 1 ms to ensure time for the UI thread try { sleep(delay); } catch (InterruptedException e) { } long start = System.currentTimeMillis(); runGameLoop(); lastTime = now; } }