0

I would like to invoke some method after specific amount of time. Here is exactly what I want to achieve: onClick button the method is invoked then application waits 200ms and invokes the same method again. The method I am talking about looks in my case like this:

private void sendMessage(String message) {
    if (mCommandService.getState() != CommandService.STATE_CONNECTED) {
        Toast.makeText(this, R.string.title_not_connected, Toast.LENGTH_SHORT).show();
        return;
    }
    if (message.length() > 0) {
        byte[] send = message.getBytes();
        mCommandService.write(send);
        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }
}

This method is used to gather string and put into OutputStream to be sent later via Bluetooth. I need to be sending this string 5 times per second so what I did so far is:

rootView.findViewById(R.id.action_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
    String message = result;
    sendMessage(message);
    sendMessage(message);
    sendMessage(message);
    sendMessage(message);
    sendMessage(message);
    }
});

But here I am just sending each of them right after another. So it should be like: sendMessage -> wait(200ms) -> sendMessage -> wait(200ms) -> sendMessage -> wait(200ms) -> sendMessage -> wait(200ms) -> sendMessage but I have no idea how could I implement that. This whole process should be invoked by only 1 button push.

I can provide necessary code right away if something important is missing.

Lisek
  • 753
  • 2
  • 11
  • 31

1 Answers1

0

You should be able to use the Thread.sleep() command to wait in between the calls to sendMessage.

EDIT: However, keep in mind that it's not a good idea to call Thread.sleep() in the Android UI thread (which is the thread that click events run on). If you do this, the UI will lock up while the thread is sleeping. See this question: How to pause / sleep thread or process in Android? for more info on how to achieve this without locking up the UI thread.

Community
  • 1
  • 1
chairbender
  • 839
  • 6
  • 14