前言

本章讲述游戏手柄按键遥感值检测

1 环境
as 4.1.*

2 代码
MainActivity.java

package com.example.testthooth1;import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.TextView;import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;public class MainActivity extends AppCompatActivity {private final  String TAG = MainActivity.class.getName() ;private TextView showtext ;private List<String> listshow ;//  private MutilTextView mutiltextview ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);showtext = (TextView)findViewById(R.id.showtext);listshow= new ArrayList<String>();}void showLog(String str){if(listshow.size() >= 50){listshow.remove(0);}listshow.add(str);showtext.setText(listshow.toString());}Dpad dpad = new Dpad();@Overridepublic boolean onGenericMotionEvent(MotionEvent event) {// Check that the event came from a game controllerif ((event.getSource() & InputDevice.SOURCE_JOYSTICK) ==InputDevice.SOURCE_JOYSTICK &&event.getAction() == MotionEvent.ACTION_MOVE) {// Process all historical movement samples in the batchfinal int historySize = event.getHistorySize();// Process the movements starting from the// earliest historical position in the batchfor (int i = 0; i < historySize; i++) {// Process the event at historical position iprocessJoystickInput(event, i);}// Process the current movement sample in the batch (position -1)processJoystickInput(event, -1);return true;}return super.onGenericMotionEvent(event);}@Overridepublic boolean dispatchKeyEvent(KeyEvent event) {if ((event.getSource() & InputDevice.SOURCE_GAMEPAD)== InputDevice.SOURCE_GAMEPAD){InputDevice mInputDevice = event.getDevice();String tcontext = "KeyEvent mInputDeviceid ="+mInputDevice.getId() +" KeyEvent="+event.getAction()+" keycode="+event.getKeyCode();Log.e(TAG,tcontext);showLog(tcontext);return  true;}return super.dispatchKeyEvent(event);}private void processJoystickInput(MotionEvent event,int historyPos) {InputDevice mInputDevice = event.getDevice();// Calculate the horizontal distance to move by// using the input value from one of these physical controls:// the left control stick, hat axis, or the right control stick.float x = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_X, historyPos);//左摇杆:float lx =  event.getAxisValue(MotionEvent.AXIS_X);float ly = event.getAxisValue(MotionEvent.AXIS_Y);//右摇杆float rx =  event.getAxisValue(MotionEvent.AXIS_Z);float ry = event.getAxisValue(MotionEvent.AXIS_RZ);//十字键float hx =  event.getAxisValue(MotionEvent.AXIS_HAT_X);float hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y);int press = -1;if (Dpad.isDpadDevice(event)) {press = dpad.getDirectionPressed(event);//  Log.e(TAG,"Dpad="+press);switch (press) {case Dpad.LEFT:// Do something for LEFT direction pressbreak;case Dpad.RIGHT:// Do something for RIGHT direction pressbreak;case Dpad.UP:// Do something for UP direction pressbreak;case Dpad.CENTER:break;case Dpad.DOWN:break;}}if (x == 0) {x = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_HAT_X, historyPos);}if (x == 0) {x = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_Z, historyPos);}// Calculate the vertical distance to move by// using the input value from one of these physical controls:// the left control stick, hat switch, or the right control stick.float y = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_Y, historyPos);if (y == 0) {y = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_HAT_Y, historyPos);}if (y == 0) {y = getCenteredAxis(event, mInputDevice,MotionEvent.AXIS_RZ, historyPos);}// Update the ship object based on the new x and y values//" NEW X="+x+" new y="+y+String tcontext = "MotionEvent mInputDeviceid ="+mInputDevice.getId() +" press="+press+  " 左摇杆("+lx+","+ly+")右摇杆("+rx+","+ry+")"+" 十字键("+hx+"."+hy+")";Log.e(TAG,tcontext);showLog(tcontext);}private static float getCenteredAxis(MotionEvent event,InputDevice device, int axis, int historyPos) {final InputDevice.MotionRange range =device.getMotionRange(axis, event.getSource());// A joystick at rest does not always report an absolute position of// (0,0). Use the getFlat() method to determine the range of values// bounding the joystick axis center.if (range != null) {final float flat = range.getFlat();final float value =historyPos < 0 ? event.getAxisValue(axis):event.getHistoricalAxisValue(axis, historyPos);// Ignore axis values that are within the 'flat' region of the// joystick axis center.if (Math.abs(value) > flat) {return value;}}return 0;}public  void onClear(View v){showtext.setText("");listshow.clear();}
}/*
JAVA FLOAT或DOUBLE保留两位小数
2015-06-26 09:28:46  By: shinyuu
shinyuu Java开发实战 0 43395 4
不管是Java Web项目还是Android项目、很多时候都需要使用到保留两位小数问题、经过查找、本文将给出几种方案、大家可根据项目需要自己决定使用那种方法方案一、四舍五入
double f = 111231.5585;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//保留两位小数方案二、DECIMALFORMAT
1、用DecimalFormat 返回的是String格式的、该类对十进制进行全面的封装、像%号、千分位、小数精度、科学计算等float price=1.2;
//构造方法的字符格式这里如果小数不足2位,会以0补足
DecimalFormat decimalFormat = new DecimalFormat(".00");
//format 返回的是字符串
String p = decimalFomat.format(price);例:new DecimalFormat("#.00").format(3.1415926)#.00 表示两位小数 #.0000四位小数 以此类推...方案三、STRING.FORMAT
double d = 3.1415926;
String result = String.format("%.2f");*/

Dpad.java
抄自 Android官方培训课程

package com.example.testthooth1;import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;public class Dpad {final static int UP       = 0;final static int LEFT     = 1;final static int RIGHT    = 2;final static int DOWN     = 3;final static int CENTER   = 4;int directionPressed = -1; // initialized to -1public int getDirectionPressed(InputEvent event) {if (!isDpadDevice(event)) {return -1;}// If the input event is a MotionEvent, check its hat axis values.if (event instanceof MotionEvent) {// Use the hat axis value to find the D-pad directionMotionEvent motionEvent = (MotionEvent) event;float xaxis = motionEvent.getAxisValue(MotionEvent.AXIS_HAT_X);float yaxis = motionEvent.getAxisValue(MotionEvent.AXIS_HAT_Y);// Check if the AXIS_HAT_X value is -1 or 1, and set the D-pad// LEFT and RIGHT direction accordingly.if (Float.compare(xaxis, -1.0f) == 0) {directionPressed =  Dpad.LEFT;} else if (Float.compare(xaxis, 1.0f) == 0) {directionPressed =  Dpad.RIGHT;}// Check if the AXIS_HAT_Y value is -1 or 1, and set the D-pad// UP and DOWN direction accordingly.else if (Float.compare(yaxis, -1.0f) == 0) {directionPressed =  Dpad.UP;} else if (Float.compare(yaxis, 1.0f) == 0) {directionPressed =  Dpad.DOWN;}}// If the input event is a KeyEvent, check its key code.else if (event instanceof KeyEvent) {// Use the key code to find the D-pad direction.KeyEvent keyEvent = (KeyEvent) event;if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {directionPressed = Dpad.LEFT;} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {directionPressed = Dpad.RIGHT;} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {directionPressed = Dpad.UP;} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {directionPressed = Dpad.DOWN;} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {directionPressed = Dpad.CENTER;}}return directionPressed;}public static boolean isDpadDevice(InputEvent event) {// Check that input comes from a device with directional pads.if ((event.getSource() & InputDevice.SOURCE_DPAD)!= InputDevice.SOURCE_DPAD) {return true;} else {return false;}}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/showtext"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"android:lines="50"android:ellipsize="end"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/clear"android:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintBaseline_toBaselineOf="@id/showtext"android:text="清理"android:onClick= "onClear"android:layout_marginLeft="8dp"/></androidx.constraintlayout.widget.ConstraintLayout>

3 说明
左右遥杆 十字键 取值

DPAD 具体取值 DPAD 可能是 key 也可能是 motion

4 demo工程
觉得有用 ,点个赞,加个关注

游戏手柄按键遥杆值检测相关推荐

  1. 最简单DIY基于STM32的远程控制电脑系统②(无线遥杆+按键控制)

    STM32库函数开发系列文章目录 第一篇:STM32F103ZET6单片机双串口互发程序设计与实现 第二篇:最简单DIY基于STM32单片机的蓝牙智能小车设计方案 第三篇:最简单DIY基于STM32F ...

  2. 电子模块 001 --- 遥杆 JoyStick

    电子模块 001 - 遥杆 JoyStick - Ongoing - 2016年8月31日 星期三 遥杆 JoyStick 模块 今天介绍:JoyStick 电子模块. 模块名称: 双轴按键摇杆 PS ...

  3. 关于游戏手柄按键的设计

    一.背景 最近开发了一个空鼠遥控器的外设产品,采用Nordic51822 MCU芯片,基于BLE4.0标准,与OTT盒子连接,同时具有遥控器.空鼠.游戏手柄的功能.其中在按键的设计这块我们走了一些弯路 ...

  4. mojing手柄遥杆控制

    using UnityEngine; using UnityEngine.UI; using System.Collections; using MojingSample.CrossPlatformI ...

  5. 20150218【改进信号量】IMX257实现GPIO-IRQ中断按键获取键值驱动程序

    [改进信号量]IMX257实现GPIO-IRQ中断按键获取键值驱动程序 2015-02-18 李海沿 前面我们使用POLL查询方式来实现GPIO-IRQ按键中断程序 这里我们来使用信号量,让我们的驱动 ...

  6. 基于STM32单片机水质检测PH值检测电导率TDS检测超声波水位检测

    系统功能设计 (末尾附文件) 本系统由STM32单片机核心板.超声波测距模块.PH值传感器模块.电导率传感器.LCD1602液晶及电源组成. 1.超声波传感器采集探测距离,PH传感器采集PH值(PH传 ...

  7. Android 小米盒子游戏手柄按键捕获 - 能获取到的 home 键依然是个痛

    Android 小米盒子游戏手柄按键捕获 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 ...

  8. 基于TPF111芯片的交流信号幅值检测

    简 介: 利用TPF111视频的自动低电平保持的功能来对于输入的交流信号进行幅值检测.的确是一个非常聪明的想法,那么效果怎么样呢?看看文中的实验结果吧. 关键词: TPF111,幅值检测,智能车竞赛, ...

  9. vue/xx/事件监听,按键与键码值

    vue中的事件监听 <!DOCTYPE html> <html lang="en"><head><meta charset="U ...

最新文章

  1. java gif 帧_在Java中修复动画gif的帧速率
  2. atom和phpcs
  3. 2.3.8 吸烟者问题
  4. c语言如何判断密码不同字符,C语言从文本文档读取字符串(用户名和密码验证)...
  5. 『设计模式』以为是个王者,后来班主任来了!设计模式--二五仔的观察者模式
  6. 给std::string增加format函数
  7. 最后2天,BDTC 2019早鸟票即将售罄,超强阵容及议题抢先曝光!
  8. MVVM框架的了解与使用
  9. python _foo __foo
  10. iOS 开发AVFoundation系统原生二维码扫描实现
  11. 青龙脚本-趣闲赚(更新)
  12. c4droid入门教程 2021.2.6更新
  13. 谷歌网页翻译失效解决方法
  14. python学习笔记 Network XHR json
  15. win快捷键_Windows 被冷落的 WIN 键,其实比你想的更好用
  16. 高中学历学了python有人要么-Python纳入浙江省高考有何意义,浙江省中学python教程...
  17. 网站被百度K了怎么办
  18. 佛说五百年的回眸才换来今生的擦肩而过!(zt)
  19. python怎么检验股票日收益率_【练习】python脚本看股票实时盈亏
  20. Dreamweaver CC 2019下载及安装

热门文章

  1. ucos操作系统(1)——OSTCBY,OSRdyGrp,OSRdyTbl
  2. stm32f103mini IO
  3. 电脑如何关闭全屏开始屏幕
  4. 前端文字下划线的模拟
  5. MAC下downie下载网页视频报错“转换错误”解决方案
  6. 驼峰命名法(camelCase)
  7. foxipdf和adobe_过去和将来的活动:Adobe Max North America和CFCAMP澳大利亚
  8. java后端根据经纬度获取地址(高德地图)
  9. 线阵相机的线扫描速率的计算方法
  10. 域名注册条件有哪些?需要提交哪些材料?