Inconsistent messaging between handler and runnable

此生再无相见时 提交于 2019-12-12 05:34:43

问题


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.

来源:https://stackoverflow.com/questions/27173558/inconsistent-messaging-between-handler-and-runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!