-1

I'm trying to implement a simple game with Android sdk. This game uses a custom view as the game area. I tried to use this code snippet to add a simple clock to the game. Basically it launches a thread which calls invalidate on the custom game view with a fixed frequency:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    class GameClock extends Thread {

        CanvasView cv;

        public GameClock(Activity ctx) {
            cv = ctx.findViewById(R.id.MainGame);
        }

        public void run() {
            while (! cv.initialized) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                }
            }

            // TODO: fix this
            while (true) {
                cv.invalidate();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                }
            }
        }
    }

    new GameClock(this).run();

}

But when I launch the app, it just hangs and doesn't display anything. Why does this happen? How can I fix it to work as expected?

xingbin
  • 27,410
  • 9
  • 53
  • 103
saga
  • 1,933
  • 2
  • 17
  • 44

1 Answers1

1

By executing new GameClock(this).run();, you just execute the run method in current thread, you need call new GameClock(this).start(); to start a new thread.

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Thanks for the fix. I corrected that and now the app crashes with this error: `08-28 21:58:44.518 3675-3695/com.example.saga.rotatingcircle E/AndroidRuntime: FATAL EXCEPTION: Thread-33681 Process: com.example.saga.rotatingcircle, PID: 3675 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.` Is it not possible to call `invalidate` on a view from another thread? – saga Aug 28 '18 at 16:29
  • @saga This helps https://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi – xingbin Aug 28 '18 at 16:32