当前位置: 首页 > >

Android监听物理按键

发布时间:

一、常用物理按键

电源键

KEYCODE_POWER

后退键

KEYCODE_BACK

菜单键

KEYCODE_MENU

HOME键

KEYCODE_HOME

相机键

KEYCODE_CAMERA

音量键

KEYCODE_VOLUME_UP / KEYCODE_VOLUME_DOWM

搜索键

KEYCODE_SEARCH

确定键

KEYCODE_DPAD_CENTER

方向键

KEYCODE_DPAD_UP      
KEYCODE_DPAD_DOWN     
KEYCODE_DPAD_LEFT      
KEYCODE_DPAD_RIGHT

键盘键

KEYCODE_0...KEYCODE_9   
KEYCODE_A....KEYCODE_Z

二、监听方法

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
Log.d("-=-","back");
return true;
}

return super.onKeyDown(keyCode, event);
}

以此类推,不过经测试现在只有返回、上下左右可以成功,其他home、多任务需要通过广播的方式去监听


这里贴上代码


public class DeviceKeyMonitor {


/**
* 参数
*/
private static final String SYSTEM_REASON = "reason";
private static final String SYSTEM_HOME_KEY = "homekey";
private static final String SYSTEM_HOME_RECENT_APPS = "recentapps";

private Context mContext;
private BroadcastReceiver mDeviceKeyReceiver = null;
private OnKeyListener mListener;

public DeviceKeyMonitor (Context context, OnKeyListener listener) {
mContext = context;
mListener = listener;
mDeviceKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
String reason = intent.getStringExtra(SYSTEM_REASON);
if (!TextUtils.isEmpty(reason)){
if (SYSTEM_HOME_KEY.equals(reason)){
mListener.onHomeClick();
} else if (SYSTEM_HOME_RECENT_APPS.equals(reason)){
mListener.onRecentClick();
}
}
}
}
};
mContext.registerReceiver(mDeviceKeyReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}

public interface OnKeyListener{
void onHomeClick();
void onRecentClick();
}

public void unregister(){
if (mDeviceKeyReceiver != null){
mContext.unregisterReceiver(mDeviceKeyReceiver);
mDeviceKeyReceiver = null;
}
}
}

activity中操作


private DeviceKeyMonitor mKeyMonitor;
private boolean isClickRecent = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mKeyMonitor = new DeviceKeyMonitor(this, this);
}

@Override
protected void onResume() {
super.onResume();
if (isClickRecent){
isClickRecent = false;
//处理按了多任务键的逻辑
} else {
//处理原本的resume逻辑
}
}

@Override
protected void onPause() {
super.onPause();
if(isClickRecent){
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
} else {
//处理原本的pause逻辑
}
}

@Override
public void onHomeClick() {
Log.d("DeviceKeyMonitor", "Home键");
}

@Override
public void onRecentClick() {
isClickRecent = true;
Log.d("DeviceKeyMonitor", "多任务键");
}

@Override
protected void onDestroy() {
mKeyMonitor.unregister();
super.onDestroy();
}

?


?



友情链接: