我想在應用程序中創建一個閃光點效果。為此我需要一個時間延遲,一個是100 ms,其它是20ms。這是我使用的代碼:
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();
}
}
問題是,當我單擊按鈕來調用該代碼,沒有出現所要的效果。所以我做了一點調試且確信它是定時調用。但是我不確定如何調用一個休眠線程。
你應該使用Handler來實現
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);
}
}
給活動設置一個主題,讓它全屏顯示。
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"