在代码中检查Android设备是否有某个硬件按钮

问题描述 投票:0回答:4

我需要检查某个Android设备的代码中是否有硬件按钮。例如,只有某些手机有搜索按钮。 那么如何检查设备是否有硬件按钮(搜索、相机、方向键等)?

java android button hardware
4个回答
9
投票

您可以使用

PackageManager.hasSystemFeature()

示例:

boolean hasCamera = 
        getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); 

您还可以通过

PackageManager
 获得一些 
Configuration
无法测试的功能,例如DPAD。

Configuration c = getResources().getConfiguration();
if(c.navigation == Configuration.NAVIGATION_DPAD)
      hasDpad = true;

唯一的例外是搜索按钮。前几天这里有一个问题,问的基本一样。我不记得任何答案,也不知道检测搜索按钮的方法,因为它不在功能列表中。 (编辑:就是这样,可能的重复线程就是我在这里提到的)


5
投票

这是检查硬件“菜单”按钮是否存在的好方法:

ViewConfiguration.get(context).hasPermanentMenuKey();

来自:https://stackoverflow.com/a/9481965 另请参阅:http://developer.android.com/reference/android/view/ViewConfiguration.html#hasPermanentMenuKey()


1
投票

我知道这篇文章已经有一年多了,但它仍然出现在谷歌搜索中(在第一页)。我想,我会发布一个关于我正在使用的内容的轻微更新或建议,以防像我这样的人正在寻找同样的东西。

public boolean onKeyDown(int keyCode, KeyEvent event) { 
           if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { 
               Toast.makeText(this,"VOL Down", Toast.LENGTH_LONG).show();
               return true;
           } else if(keyCode == KeyEvent.KEYCODE_SEARCH){
               Toast.makeText(this,"search", Toast.LENGTH_LONG).show();
               return false;
           }else{
               Toast.makeText(this,"Vol Up", Toast.LENGTH_LONG).show();
               return true;
               //return super.onKeyDown(keyCode, event); 
           }
    }

我已经将 onCreate() 放在了外面。这在我的 Thunderbolt 上运行良好(rooted 运行 MikMik GingerGrits)


0
投票

可以使用这些 API 来检查设备是否有特定的物理按键,按下时会发送特定的键码。

private fun logDeviceKeyCapabilities() {
    Log.i(TAG, "Build.MODEL: ${Build.MODEL}")
    val deviceHasKey = KeyCharacterMap.deviceHasKey(300)
    Log.i(TAG, "deviceHasKey(300): $deviceHasKey")
    InputDevice.getDeviceIds().toList()
        .map { id -> id to InputDevice.getDevice(id) }
        .mapNotNull { (id, device) -> device?.let { id to device } }
        .forEach { (id, device) -> logInputDeviceInfo(id, device) }
}

private fun logInputDeviceInfo(id: Int, device: InputDevice) {
    Log.i(TAG,"InputDevice($id).name: ${device.name}")
    Log.i(TAG,"InputDevice($id).descriptor: ${device.descriptor}")
    Log.i(TAG,"InputDevice($id).productId: ${device.productId}")
    Log.i(TAG,"InputDevice($id).vendorId: ${device.vendorId}")
    Log.i(TAG,"InputDevice($id).device.hasKeys(300): ${device.hasKeys(300).toList()}")
    Log.i(TAG,"InputDevice($id).device.hasKeys(Int.MAX_VALUE): ${device.hasKeys(Int.MAX_VALUE).toList()}")
    Log.i(TAG,"InputDevice($id).device.hasKeys(Int.MIN_VALUE): ${device.hasKeys(Int.MIN_VALUE).toList()}")
    Log.i(TAG,"InputDevice($id).device.hasKeys(0): ${device.hasKeys(0).toList()}")
    Log.i(TAG,"InputDevice($id).device.hasKeys(KeyEvent.KEYCODE_BACK): ${device.hasKeys(KeyEvent.KEYCODE_BACK).toList()}")
}
© www.soinside.com 2019 - 2024. All rights reserved.