java – Getting dualshok 4 positions-ThrowExceptions

Exception or error:

I trying to make a simple app that can be controlled by my gamepad (dualshok 4) and i stacked at getting current positions axies and buttons of my gamepad.

Below my code that i already tried:

class MainActivity : AppCompatActivity(), OnGenericMotionListener{

    override fun onGenericMotion(p0: View?, p1: MotionEvent?): Boolean {
        if (p1!!.getSource() and InputDevice.SOURCE_CLASS_JOYSTICK !== 0 && p1!!.getAction() === MotionEvent.ACTION_MOVE) {
            val motionRanges = p1!!.getDevice().getMotionRanges()
            for (mr in motionRanges) {
                val axis = mr.getAxis()
                if (p1.getAxisValue(axis) > 0.5 || p1.getAxisValue(axis) < -0.5) {
                    Log.d("JOY_DEBUG", "Axis found: " + MotionEvent.axisToString(axis))
                }
            }
        } else {
            Log.i("JOY_DEBUG", "Not a joystick event.")
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

The method “onGenericMotion” seems like not working, because it is not called even if i did this:

class MainActivity : AppCompatActivity(), OnGenericMotionListener{

    override fun onGenericMotion(p0: View?, p1: MotionEvent?): Boolean {

        Log.i("JOY_DEBUG", "method was called")

        if (p1!!.getSource() and InputDevice.SOURCE_CLASS_JOYSTICK !== 0 && p1!!.getAction() === MotionEvent.ACTION_MOVE) {
            val motionRanges = p1!!.getDevice().getMotionRanges()
            for (mr in motionRanges) {
                val axis = mr.getAxis()
                if (p1.getAxisValue(axis) > 0.5 || p1.getAxisValue(axis) < -0.5) {
                    Log.d("JOY_DEBUG", "Axis found: " + MotionEvent.axisToString(axis))
                }
            }
        } else {
            Log.i("JOY_DEBUG", "Not a joystick event.")
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Then in the Logcat i do not see anything.

Please, help

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *