Android中home键和电源键的监听

2019-07-13 23:03发布

在项目开发中我们经常需要监听一些按钮进行事件 处理,比如返回键,home键,电源键等等,监听返回键我们只要重写onkeyDown方法即可,而在home键和电源键需要我们通过广播去实现。package com.example.hello; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //home键监听 final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(homePressReceiver, homeFilter); //电源键监听 final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); registerReceiver(mBatInfoReceiver, filter); } private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() { final String SYSTEM_DIALOG_REASON_KEY = "reason"; final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); if(reason != null&& reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { System.out.println("home键监听"); } } } }; private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if(Intent.ACTION_SCREEN_OFF.equals(action)) { System.out.println("电源键监听"); } } }; }