Search code examples
androidbuttonrecordonlongclicklistener

Android button onLongClick, how to get the listener when the button is released from a long click


I'm following this tutorial to implement a recorder in Android, which contains the code below, when the button is held, start recording, when released, stop recording, but I can't find the listener when the button is released, any advice? Thank you in advance

button.setOnLongClickListener(new View.OnLongClickListener() {          
        @Override
        public boolean onLongClick(View arg0) {
            startRecording();
            return false;
        }           
    });

private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(voiceFileName);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }
    mRecorder.start();
}

private void stopRecording() {
    mRecorder.stop();
    mRecorder.release();
    mRecorder = null;
}

Solution

  • You shouldn't implement the longclicklistener, you should implement the OnTouchListener.

    There you will have the touch event, and do this:

    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP){
    
                stopRecording();
                return true;
            }else{
                startRecording();
                return true;
            }
            return false;
        }
    });