androidandroid-layoutchatandroid-keypadandroid-touch-event

How to handle if user stopped after typing in edittext android?


I am developing an app for chat. I can get event to update typing status when user typed or when user erased fully, I can update as "not typing status" and showing as online. Till this process works fine.

But problem is when user typed some lines and stopped, I should not show typing which is applied in whatsapp. How to handle this?

Here is code what i done is.

        ChatMsg.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start,
                    int before, int count) {
                   if (edtChatMsg.getText().toString().trim().length() > 0) {
                    if (!isTyping) {
                            isTyping = true;
                            serviceCall();
                          }
                  else{
                      isTyping = false;
                        serviceCall();
                      }
            }
        so at result
    @Override
     protected void onTyping(String message) {
    if (message.equalsIgnoreCase("Typing…")) {
        txtUserPersonStatus.setText("Typing…");
    } else {
        txtUserPersonStatus.setText("Online");
    }
}

My question is how to handle when user typed in keyboard for a while and then stop.

Thanks.


Solution

  • Basically you need to implement some sort of timeout. Every time the user types something, you have to schedule a timeout and reset any timeouts you have scheduled before. Thus when the user stops typing the timer gets triggered after the specified time.

    You can do this with a Handler for example:

    final int TYPING_TIMEOUT = 5000; // 5 seconds timeout
    final Handler timeoutHandler = new Handler();
    final Runnable typingTimeout = new Runnable() {
        public void run() {
            isTyping = false;
            serviceCall();
        }
    };
    
    ChatMsg.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // reset the timeout
            timeoutHandler.removeCallbacks(typingTimeout);
    
            if (edtChatMsg.getText().toString().trim().length() > 0) {
                // schedule the timeout
                timeoutHandler.postDelayed(typingTimeout, TYPING_TIMEOUT);
    
                if (!isTyping) {
                    isTyping = true;
                    serviceCall();
                }
            }
            else {
                isTyping = false;
                serviceCall();
            }
        }
    });