Mina Dahesh Mina Dahesh - 6 months ago 20
Android Question

How to make screen backlight on/off like blinking during period of time in Android?

Is it possible to make the screen backlight of device turn on and off during e.g 30 seconds so that it looks like a blinking screen?

public class blinking extends TimerTask {
@Override
public void run() {
PowerManager powerMan = (PowerManager) *getSystemService*(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerMan.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakelockTag");

boolean screenOn = false;
for (int i = 0; i < 30; i++) {
if (screenOn) {
wakeLock.acquire();
screenOn = false;
} else {
wakeLock.release();
screenOn = true;
}
}
}
}


And use this code in my Activity class (for calling Blinking class):

Timer mTimer = new Timer();
mTimer.schedule( new blinking(), 30000 );

Answer

Try this in your class:

Create the power managr parameter

PowerManager powerMan = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerMan.newWakeLock(
                     PowerManager.SCREEN_DIM_WAKE_LOCK | 
                     PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakelockTag");

Call the timer

Timer timer = new Timer(); 
timer.schedule( new FlashingTimerTask(), 30000 );

And for the Timer task:

public class FlashingTimerTask extends TimerTask{

    @Override
    public void run() {
            boolean screenOn = false;
            for (int i = 0; i < 30; i++) {
                if (screenOn) {
                    wakeLock.acquire();
                    screenOn = false;
                } else {
                    wakeLock.release();
                    screenOn = true;
                }
            }
    }
}