我想在屏幕关闭时跟踪音量键。如何将我的代码放在receive方法中?
我想在用户按下音量调低键和屏幕熄灭时打开手电筒。
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);
}
}
答案 0 :(得分:0)
您无需在onReceive()
内设置事件侦听器。试试这个
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;
}