Paul
Paul

Reputation: 5974

Handler running more often than it should? (postDelayed)

I am connecting to a terminal emulator using a library in android, this connects to a serial device (a switch) and shows me sent/received data.

When I receive data the method below is automatically run. When I receive data I wanted to update the emulator screen using invalidate in the onDataReceived method, however this was not working for some reason and so I created a handler to do it every 1 second instead and that works.

public void onDataReceived(int id, byte[] data) 
{
    dataReceived = new String(data);
    ((MyBAIsWrapper) bis).renew(data);
    mSession.write(dataReceived);

    mSession.notifyUpdate();
    viewHandler.post(updateView);
}

Now I wanted to test the data received for certain characters so I made a for loop in onDataReceived, again this didn't work, it would only see the character now and again, missing some of them. So I added the loop to the handler instead:

Handler viewHandler = new Handler();
Runnable updateView = new Runnable()
{
    @Override
    public void run() 
 {
        //update screen ever 1000ms
        mEmulatorView.invalidate();

    //should check data received every 1000ms
    for(int i = 0; i < dataReceived.length(); i++)
        {           
            if(dataReceived.charAt(i) == '>')
                {

                     Log.d(TAG, "found >");
                }

            if(dataReceived.charAt(i) == '#')
                {

                     Log.d(TAG, "found #");     
                }
        }
        viewHandler.postDelayed(updateView, 1000);
  }

};

My problem is that while I can see the screen gets updated once per second, in the logs I can see I find the characters much more frequently, it is printing them out to the log 100s of times, why is this?

Upvotes: 1

Views: 428

Answers (1)

Opiatefuchs
Opiatefuchs

Reputation: 9870

I don´t really know, but the reason could be, because the runnable is not stopped. Just make an condition that the runnbale should only start if this condition is true. So if it is false, the runnable stops automatically, for example:

        @Override
public void run() 
 {
    //update screen ever 1000ms
    mEmulatorView.invalidate();

     if(yourCondition==true){ //put here a condition that the runnable only starts if this is true
//should check data received every 1000ms
for(int i = 0; i < dataReceived.length(); i++)
    {           
        if(dataReceived.charAt(i) == '>')
            {

                 Log.d(TAG, "found >");
            }

        if(dataReceived.charAt(i) == '#')
            {

                 Log.d(TAG, "found #");     
            }
    }
    viewHandler.postDelayed(updateView, 1000);
    }
   }

  };

Upvotes: 1

Related Questions