Android : Android Detect Pressing On Power Key

on Sunday, September 14, 2014


My Application needs to know if the screen went off due to timeout or the user clicked the power button.


I decided to check if the power button was pressed. I read some Q&A here and came up with this :



public class MyActivity extends Activity {

/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button down detected");
return true;
}
return false;
}


@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button up detected");
}
return false;
}
}


I also added this:



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


This doesn't work, it doesn't print the log.


0 comments:

Post a Comment