Android实现检测实体按键事件并屏蔽
本文实例为大家分享了Android实现检测实体按键事件并屏蔽的具体代码,供大家参考,具体内容如下
效果图:
文章图片
新建服务类MyKeyEventService.java。用于监听电源键的触发。
public class MyKeyEventService extends Service {@Nullable@Overridepublic IBinder onBind(Intent intent) {return null; }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); final BroadcastReceiver mReceiver = new MainActivity.ScreenReceiver(); registerReceiver(mReceiver, filter); return super.onStartCommand(intent, flags, startId); }public class LocalBinder extends Binder {MyKeyEventService getService() {return MyKeyEventService.this; }}}
注册服务类,AndroidManifest.xml文件。
【Android实现检测实体按键事件并屏蔽】主界面MainActivity.java。
public class MainActivity extends AppCompatActivity {private static final String TAG = "MyKeyEvent"; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, LockService.class)); }@Overrideprotected void onDestroy() {super.onDestroy(); stopService(new Intent(MainActivity.this, LockService.class)); }@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_VOLUME_UP:Log.i(TAG, "onKeyDown: vol+ down"); return true; //break; case KeyEvent.KEYCODE_VOLUME_DOWN:Log.i(TAG, "onKeyDown: vol- down"); return true; //break; case KeyEvent.KEYCODE_POWER:Log.i(TAG, "onKeyDown: power down"); return true; //break; default:break; }return super.onKeyDown(keyCode, event); }@Overridepublic boolean onKeyUp(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_VOLUME_UP:Log.i(TAG, "onKeyDown: vol+ up"); return true; //break; case KeyEvent.KEYCODE_VOLUME_DOWN:Log.i(TAG, "onKeyDown: vol- up"); return true; //break; case KeyEvent.KEYCODE_POWER:Log.i(TAG, "onKeyDown: power up"); return true; //break; default:break; }return super.onKeyUp(keyCode, event); }static class ScreenReceiver extends BroadcastReceiver {@Overridepublic void onReceive(final Context context, final Intent intent) {//Log.e(TAG, "onReceive " + intent.getAction()); if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {// do whatever you need to do hereLog.e(TAG, "Screen Off"); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {// and do whatever you need to do hereLog.e(TAG, "Screen On"); }}}}
如果不想屏蔽系统按键事件,则把**return true; **加上注释。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
推荐阅读
- android第三方框架(五)ButterKnife
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- Android中的AES加密-下
- 带有Hilt的Android上的依赖注入
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Java|Java OpenCV图像处理之SIFT角点检测详解
- Node.js中readline模块实现终端输入