Skip to content

Instantly share code, notes, and snippets.

@stealthcopter
Last active March 7, 2020 12:01
Show Gist options
  • Save stealthcopter/b11980d08a1baa3395a6 to your computer and use it in GitHub Desktop.
Save stealthcopter/b11980d08a1baa3395a6 to your computer and use it in GitHub Desktop.
package com.example
import android.util.Log;
import android.view.KeyEvent;
/**
* Created by mat on 10/04/14.
*
* Allows a secret combination of volume up / volume down presses to trigger something.
* I.E. reveal a hided debug menu when a combination is entered
* In the example below 2431 would be triggered by pressing
* down down, up up up up up, down down down, up
* or
* up up, down, down, down, down, up, up, up, down
*/
private VolumeCombination volumeCombination;
// Create a new VolumeCombination with secret code and a listener for unlocking
volumeCombination = new VolumeCombination("2431", new VolumeCombination.UnlockListener() {
@Override
public void onUnlock() {
Toast.makeText(StartActivity.this, "Unlocked ^_^", Toast.LENGTH_SHORT).show();
}
});
// Override onKeyDown in your activtiy or fragment and pass the event to
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (volumeCombination.checkVolumeCombination(keyCode, event)) return true;
return super.onKeyDown(keyCode, event);
}
*/
public class VolumeCombination {
private static final long TIMEOUT_PREVIOUS_PRESS = 2000;
public UnlockListener unlockListener;
public String secretCode;
public String currentAttempt = "";
public long prevPress = 0;
public int curNo = 0;
public int prevKey = -1;
public VolumeCombination(String secretCode, UnlockListener unlockListener){
this.secretCode = secretCode;
this.unlockListener = unlockListener;
}
interface UnlockListener{
public void onUnlock();
}
public boolean checkVolumeCombination(int keyCode, KeyEvent keyEvent){
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
if (System.currentTimeMillis()-prevPress>TIMEOUT_PREVIOUS_PRESS){
// If user doesn't press a volume for a while, clear the attempt
Log.i("VOLUME COMBINATION: ", "Timeout...");
curNo=0;
prevKey=-1;
currentAttempt="";
}
if (prevKey==keyCode || prevKey==-1){
// If it's the same key add one to current letter of code
curNo++;
}
else{
// If it's different move on to next letter
currentAttempt += curNo;
curNo=1;
}
Log.i("VOLUME COMBINATION: ", ""+currentAttempt+curNo);
if (secretCode.equals(currentAttempt+curNo)){
unlockListener.onUnlock();
}
// If our current string is too long, drop the start
if (currentAttempt.length()==secretCode.length()) currentAttempt = currentAttempt.substring(1);
prevKey = keyCode;
prevPress = System.currentTimeMillis();
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment