Search code examples
androidloopsdelaysleepkeystroke

Delay For Loop for a specific amount of time - Android


I am trying to simulate a keystroke by setting setPressed to true and then via a postDelay setting setPressed to false a few ticks later. My issue is this works perfectly when applied once but when I try to iterate through a list with multiple elements the delays I believe run over one another. The iterations are much too fast. I believe the solution would be to delay the loop from iterating for a period of time just longer than the postDelayed, but I am not having much success with this either.

public void myOnClickListener(View view) {

    switch (view.getId()) {

    case R.id.test:
        //adds two random digits to list
        addRandomDigits(2);

        int size = list.size();
        System.out.println("Size: " + size);
            tmpButton = map.get(list.get(list.size()-1));
            tmpButton.setPressed(true);
            tmpButton.postDelayed(new Runnable() {
                public void run() {
                    tmpButton.setPressed(false);
                }
            }, 200);

        Log.e("**droid", "Droid sequence: " + getArrayListAsString(list));
        break;

If this solution does not seem to be the most efficient, logical, etc., I am wide open to any suggestions. Thanks in advance.


Solution

  • Instead of loop, i would like to suggest you to use TimerTask Class for the execution at a particular time period.

    private class myLoop extends TimerTask
    {
           public void run()
           {
               // Place your code here.
    
               addRandomDigits(2);
    
               int size = list.size();
               System.out.println("Size: " + size);
               tmpButton = map.get(list.get(list.size()-1));
               tmpButton.setPressed(true);
               tmpButton.setPressed(false);
    
              Log.e("**droid", "Droid sequence: " + getArrayListAsString(list));
              break;
           }
    }
    

    you need to make your tmpButton as static.