I want to track volume key down when screen was off. How can I put my code in on receive method?
I want to turn on flashlight when user pressed volume down key and when screen goes off.
MyReceiver.java :
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
// Log.i("via Receiver","Normal ScreenOFF" );
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
} else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
You don't need to set event listener inside onReceive()
. Try like this
setOnKeyListener(new View.OnKeyListener() {
@Override public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (screenOff) {
// turn on torch
return true;
}
}
return false;
}