0

I've written an android program involving a counter that is increased by one when the volume button is pressed. It's also supposed to turn the screen off when this button is pressed and wait 5 seconds of inactivity before turning it back on. But nothing is happening besides the counter increasing when I run the application, i.e. the screen doesn't turn off.

Here is my java class:

public class MainActivity extends Activity {

private TextView counterTextView;
int count;

PowerManager.WakeLock wakeLock;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    counterTextView = (TextView) findViewById(R.id.counterTextView);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getRepeatCount() == 0) {
        count++;
        counterTextView.setText(" " + count + " ");

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
        wakeLock.acquire();

        new Handler().postDelayed(screenOnRunnable(), 5000);

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

private Runnable screenOnRunnable() {
    return new Runnable() {

        @Override
        public void run() {

            wakeLock.release();

        }
    };
}

}

I also added the WAKE_LOCK permission in the manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />

I have no idea what's wrong... any help would be greatly appreciated.

OHS
  • 185
  • 1
  • 2
  • 12
  • You are not passing the context and not using while creating the accessing POWER_SERVICE. – smali Apr 04 '15 at 11:35

1 Answers1

0

There are few problems with your code.

1. You are using wrong wakelock

PowerManager.PARTIAL_WAKE_LOCK - Ensures that the CPU is running; the screenand keyboard backlight will be allowed to go off

you should use PowerManager.FULL_WAKE_LOCK for your purpose but it is a deprecated api so it is not preferred and instead now a days FLAG_KEEP_SCREEN_ON is used for the same purpose.

2. You are expecting the device to turn off immediately after 5 seconds.

This will not happen because you are not considering the minimum time to sleep that is set in

Settings--->Display----->Sleep

After you will release the full wakelock the device will take the above time to go to sleep.

I hope this will give you some clarification as to why your code is not working.

Sam
  • 452
  • 5
  • 15