您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。