您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要为大家展示了“Android如何实现检测实体按键事件并屏蔽”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Android如何实现检测实体按键事件并屏蔽”这篇文章吧。
效果图:
新建服务类MyKeyEventService.java。用于监听电源键的触发。
public class MyKeyEventService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public 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文件。
<service android:name=".MyKeyEventService"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </service>
主界面MainActivity.java。
public class MainActivity extends AppCompatActivity { private static final String TAG = "MyKeyEvent"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, LockService.class)); } @Override protected void onDestroy() { super.onDestroy(); stopService(new Intent(MainActivity.this, LockService.class)); } @Override public 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); } @Override public 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 { @Override public 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 here Log.e(TAG, "Screen Off"); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // and do whatever you need to do here Log.e(TAG, "Screen On"); } } } }
如果不想屏蔽系统按键事件,则把**return true;**加上注释。
以上是“Android如何实现检测实体按键事件并屏蔽”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。