0

I'm trying to update UI from a background thread through a Handler. Runnable sends periodically (minimum once every two seconds, maximum 16 times per second) new data to handler to be updated. On my runnable class I have a flag for starting/stoping loop -there are methods on main class attached to buttons for this task-.

I have several problems with this:

  1. First message received is always 0
  2. After a few loops, message received by handler is always 0
  3. From time to time (sorry, poor precision, I know), pressing stop produces an IllegalStateException. Here's the code (simplified):

Main Activity:

public class MainActivity extends Activity
{

    OtherClass otherObbject;
    Thread otherClassThread;
    Handler handler;
    TextView txtBeat;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtBeat = (TextView) findViewById(R.id.txtBeat);

        handler = new Handler()
        {
            int beat;

            @Override
            public void handleMessage(Message msg)
            {
                msg = this.obtainMessage();
                beat = msg.getData().getInt("beat");
                txtBeat.setText(String.valueOf(beat));
            }
        };
    }

    public void onPlay(View v)
    {
        otherObbject = new OtherClass(handler);
        otherClassThread = new Thread(otherObbject);
        otherObbject.start();
        otherClassThread.start();
    }

    public void onStop(View v)
    {
        otherObbject.stop();
    }

}

Runnable class:

public class OtherClass implements Runnable
{
    private Boolean isPlaying;
    private Handler mHandler;
    private int beatMaximum;
    private long waitTime;
    private long maxWait;

    public OtherClass(Handler handler)
    {
        isPlaying = false;
        mHandler = handler;
        beatMaximum = 4;
        waitTime = 30;
        maxWait = 500;
    }

    @Override
    public void run()
    {
        int counter = 0;
        int beat = 1;
        Bundle bundle = new Bundle();
        Message msg = new Message();

        while (isPlaying)
        {
            if(counter == 0)
            {
                //Do some stuff

                System.out.println(beat);
                bundle.putInt("beat", beat);
                msg.setData(bundle);
                mHandler.sendMessage(msg);

                if (beat == beatMaximum)
                    beat = 1;
                else
                    beat++;
            }
            else
                waitThread();

            if ((counter += waitTime) >= maxWait)
                counter = 0;
        }
    }

    private void waitThread()
    {

        try
        {
            Thread.currentThread().sleep(waitTime);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void start()
    {
        isPlaying = true;
    }

    public void stop()
    {
        isPlaying = false;
    }
}

And exception:

FATAL EXCEPTION: main
java.lang.IllegalStateException: The specified message queue synchronization  barrier token has not been posted or has already been removed.
        at android.os.MessageQueue.removeSyncBarrier(MessageQueue.java:266)
        at android.os.Looper.removeSyncBarrier(Looper.java:242)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:990)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
        at android.view.Choreographer.doCallbacks(Choreographer.java:555)
        at android.view.Choreographer.doFrame(Choreographer.java:525)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

I'm stuck with these problems for several days. I didn't tried AsyncTask, because it can be running for minutes, and from Google documentation:

AsyncTasks should ideally be used for short operations (a few seconds at the most.)

Thanks for your time.

Dani
  • 43
  • 1
  • 6
  • in handleMessage() remove msg = obtainMessage() – pskink Nov 27 '14 at 15:10
  • Done, but I only get first message. Right after that app crashes whith posted exception :/ – Dani Nov 27 '14 at 15:29
  • may i ask what do you need that background thread for, as it doesn't do any hard work? – pskink Nov 27 '14 at 15:32
  • Sure, I didn't posted irrelevant code. It's a metronome; background thread is feeding constantly an AudioTrack object which executes beeps. I want to update UI according with tempo beat. – Dani Nov 27 '14 at 15:39
  • you dont need a thread for this, just use a Handler or CountDownTimer – pskink Nov 27 '14 at 15:42
  • Timers don't work fine for this, as long as I need rock solid timing with a few milliseconds between beeps, otherwise is totally useless. After a lot of research and tests, the only way I could provide solid timing was with an AudioTrack in streaming mode fed continuously with beeps and silence. Anyway, I'll check how to do it just using a handler. – Dani Nov 27 '14 at 15:52
  • i didn't mean Timers/TimerTasks, i meant Handler or CountDownTimer – pskink Nov 27 '14 at 15:55
  • Ok, I've just tried with CountDownTimer and accuracy is a pain, as expected. I presume same behaviour with Handler, so let's get back to my original question which is how to solve my issues with messaging – Dani Nov 27 '14 at 17:55
  • ok but did you tried Handler.send[Empty]Message[Delayed/AtTime] ? i think AtTime version would be helpful – pskink Nov 27 '14 at 17:59
  • No, I didn't. Clocks just don't work for this, as their accuracy depends on CPU load, and again, I need very high precision. Believe me, I spent a lot of hours with it. – Dani Nov 28 '14 at 06:28
  • what thread do you want to use your AudioTrack in? in the background thread or the main UI thread? if the background (and i believe this is your choice) you don't need to sleep at all, just write the data to the AudioTrack and call Handler.obtainMessage(what).sendToTarget(); to notify the UI thread – pskink Nov 28 '14 at 09:00
  • Yes, it's in the background. If you look at my code I'm not sleeping anything. I'm feeding AudioTrack where you can see "do some stuff", then, I put data into message and send it to handler. I've just tried the way you say (sendToTarget()), and I get same behaviour as doing it with sendMessage(), that is, first comes always as zero, second is 2 as expected, and after a few time all income messages are 0 while correct number is sent. – Dani Nov 28 '14 at 09:34
  • I also see waitThread method called in the else branch, can you post your current code? – pskink Nov 28 '14 at 09:42
  • Yes, sorry. That wait is only for simulation purposes. In my code I inject silence into AudioTrack at that point. – Dani Nov 28 '14 at 16:28
  • So post your code with what i suggested: Handler.obtainMessage(what).sendToTarget(); – pskink Nov 28 '14 at 16:44
  • "Timers don't work fine for this, as long as I need rock solid timing with a few milliseconds between beeps, otherwise is totally useless" -- then you will need to implement the whole thing the way you would a game. You are not going to get "rock solid timing" by using `Handler`. Grab a book on Android game development, see how they implement a 2D game using a `Canvas`, and adapt those techniques to your app. – CommonsWare Nov 28 '14 at 16:50
  • All right, I'll take a look at game development techniques – Dani Dec 02 '14 at 10:43

0 Answers0