0

I just started android studio. I am currently making a game. I read that you should separate ui and game logic / rendering on different threads. I currently have a class game that extends activity running on the ui-thread. Game also has a handler and a Game View class. The Game View is the game world, it is run on a separate thread i.e worker thread. I am trying the wrap my head around how to communicate between these, since for example i need to update the health bar on the ui thread when the player takes damage on the worker thread.

Fortunately i have a reference to the handler in my Game View class, so i should be able to communicate between these. My issue is that publish takes a log record as a parameter which would need to be deciphered in the other end using a switch. Would it instead be a good practice the create a custom handler that has appropriate methods like this:

  this.handler = new CustomHandler() {
            public void updateHealthBar(int damage) {
                //find ui element and update ...
            }

            ...Other methods

            @Override
            public void publish(LogRecord logRecord) {

            }

            @Override
            public void flush() {

            }

            @Override
            public void close() throws SecurityException {

            }
        };

Instead of this:

  this.handler = new CustomHandler() {
                @Override
                public void publish(LogRecord logRecord) {
                    switch(logRecord.Message()) {
                        case "Update Health Bar":
                           //find ui element and update ...
                        ... check for other cases

                    }
                }

                @Override
                public void flush() {

                }

                @Override
                public void close() throws SecurityException {

                }
            };

How do i even get the integer value that i should update the ui with from a logRecord? I need one variable that says what to update but also some value that says by how much...

Hamza
  • 45
  • 8
ojoj kolol
  • 79
  • 6
  • Get Handler from UIThread and Post it. Check https://stackoverflow.com/questions/4388415/call-main-thread-from-secondary-thread-in-android/45984354#45984354 – Ravindra babu Sep 14 '17 at 10:24
  • @Ravindrababu there is no handleMessage method in handler... only publish. – ojoj kolol Sep 15 '17 at 21:58
  • @Ravindrababu also, i cant user looper.getMainLooper like the example in your link. The argument is of type message aswell not LogRecord that i have to use ... – ojoj kolol Sep 15 '17 at 22:01
  • Lol the problem was that i was importing the wrong package..... I used the handler for logging. Thats why i couldent find handleMessage / message etc... – ojoj kolol Sep 16 '17 at 01:13

0 Answers0