Reputation: 29
I try to toggle the screen brightness low and high periodically (1s) and I thought this code should work:
SystemClock.sleep(1000);
params.screenBrightness = 0;
getWindow().setAttributes(params);
SystemClock.sleep(1000);
params.screenBrightness = 1;
getWindow().setAttributes(params);
I have tried these codes but it only completes the second one (or last one if i extend the codes) (i.e. brightness=1). As I doubt about that so I put a variable int i = 0, then i++ after each sleep function, it shows me i = 2 after all (by displaying string). I think Android does the sum but my screen just react to the last setting but not the intermediate commands. Do you have any idea why it is that and how can I toggle the screen brightness?
I also try to use "for" loop but no luck.
Hope to receive your comments asap.
Cheers,
Upvotes: 1
Views: 2644
Reputation: 86948
I'm not sure why you want to brighten and darken your screen every other second... But if you want run code on a time delay consider using a Handler and Runnable:
import android.view.WindowManager.LayoutParams;
public class Example extends Activity {
private LayoutParams mAttributes;
private Handler mHandler = new Handler();
private Window mWindow;
private Runnable onEverySecond = new Runnable() {
public void run() {
if(mAttributes.screenBrightness != LayoutParams.BRIGHTNESS_OVERRIDE_FULL)
mAttributes.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
else
mAttributes.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
mWindow.setAttributes(mAttributes);
mHandler.postDelayed(onEverySecond, 1000);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWindow = getWindow();
mAttributes = mWindow.getAttributes();
mHandler.post(onEverySecond);
}
}
Upvotes: 5
Reputation: 6250
You can solve that either with a Handler and posting delayed tasks in runnables to it, or by using a timer. I'd go for the second approach since what you need is to repeat tasks rather than executing tasks sequentially.
Upvotes: 0