Is it safe to use Java Threads in the same way as desktop applications?

android, java, multithreading

Solution

You can use the `Thread` directly but there are some catches in Android

- Do not block the UI thread

- Do not access the Android UI toolkit from outside the UI thread

Android documentation on Processes and Threads provides ample guidelines to help you get started.

Use AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

Problem

The Android must manage the thread or can be used a code like this: ``` public class GameThread implements Runnable { public void run() { while (!finished) { //game work try { Thread.sleep(fps); } catch (InterruptedException e) { // Interruptions here are no big deal. } } } } ```

Original source