Search code examples
androidmultithreadingtimesleepdelay

Time Delay In Android


So I am trying to create a "strobe" light effect in my app.

To do this I need a time delay, one of 100ms the other of 20.

Here is the code I'm using.

Thread timer = new Thread();
    long longTime = 100;
    long shortTime = 20;
    for (int x = 0; x < 2000000; x++)
    {
        layout.setBackgroundColor(background);
        try {
            timer.sleep(longTime);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        layout.setBackgroundColor(backgroundBlack);
        try {
            timer.sleep(shortTime);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The issue I have is that when I click the button to call that code, nothing happens. So I've done a bit of debugging and am pretty sure it is the timing call. I have never programmed in Java before so I am unsure how to call a Thread Sleep.


Solution

  • You could use a Handler as below to achieve this.

    public class Strobe extends Activity {
    
        private LinearLayout mLinearLayout;
    
        private Handler mHander = new Handler();
    
        private boolean mActive = false;
        private boolean mSwap = true;   
    
        private final Runnable mRunnable = new Runnable() {
    
            public void run() {         
                if (mActive) {
                    if (mSwap) {                    
                        mLinearLayout.setBackgroundColor(Color.WHITE);
                        mSwap = false;
                        mHander.postDelayed(mRunnable, 20);
                    } else {
                        mLinearLayout.setBackgroundColor(Color.BLACK);
                        mSwap = true;
                        mHander.postDelayed(mRunnable, 100);
                    }
                }           
            }
        };
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mLinearLayout = (LinearLayout) findViewById(R.id.strobe);
            startStrobe();
        }
    
        private void startStrobe() {        
            mActive = true;
            mHander.post(mRunnable);
        }
    }
    

    Set a Theme to the Activity to make it full screen.

    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"