ExpressionManager.java 14.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
package com.wd.speech.manager;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.ColorRes;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
import com.wd.base.log.Logger;
import com.wd.speech.dialog.VoiceSearchDialog;
import com.wd.speech.R;
import com.wd.speech.SpeechCompServiceImpl;
import com.wd.speech.listener.SpeechResultCallback;
import com.wd.speech.utils.KeyBoardObserver;
import com.wd.speech.utils.KeyboardHelper;
import com.wd.speech.view.BackEditText;
import com.wd.speech.view.MeasureFrameLayout;
import com.wd.common.permissions.IPmsCallBack;
import com.wd.common.permissions.PermissionsUtils;
import com.wd.foundation.wdkit.utils.SpUtils;
import com.wd.foundation.wdkit.utils.ToastNightUtil;
import com.wd.foundation.wdkitcore.thread.ThreadPoolUtils;
import com.wd.foundation.wdkitcore.tools.ResUtils;
import com.wd.foundation.wdkitcore.tools.StringUtils;

/**
 * @author LiuKun
 * @date 2023/5/2  17:24
 * @Description:表情键盘切换
 */
public class ExpressionManager implements KeyBoardObserver {


    private final Activity activity;
    private SpeechCompServiceImpl speechCompService;

    private final View voiceLayout;

    private BackEditText editText;

    private final ImageView voiceBtn;

    /**
     * 是否限制字数
     */
    private boolean isLimit = false;
    private int mMaxInputLength = 1000;
    /**
     * 当文字超出最大值时是否改变提示文字颜色
     */
    private boolean isChangeInputCountColor = false;
    private int[] changeColors;
    private MeasureFrameLayout rootLayout;

    /**
     * 0:show keyboard 1:show voice 2:show expression
     */
    private int showButton = 1;
    // 语音输入的布局
    private FrameLayout flVoiceInput;
    private TextView voiceBottomTip;

    /**
     * 语音输入动画
     */
    private LottieAnimationView lavVoiceInput;
    private LottieAnimationView lavVoiceInputsteptwo;

    /**
     * 是否正在录音
     */
    private boolean isRecording = false;
    private boolean isstart;

    /**
     * 使用类型,0:默认 1:语音搜索
     */
    private int useType = 0;

    private VoiceSearchDialog voiceSearchDialog;

    /**
     * 构造方法
     */
    public ExpressionManager(VoiceSearchDialog voiceSearchDialog,Activity activity, SpeechCompServiceImpl speechCompService,
                             View voiceLayout, BackEditText inputEt, ImageView voiceBtn,int useType) {
        this.voiceSearchDialog = voiceSearchDialog;
        this.activity = activity;
        this.speechCompService  = speechCompService;
        this.voiceLayout = voiceLayout;
        this.editText = inputEt;
        this.voiceBtn = voiceBtn;
        this.useType = useType;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        initView();
        addListener();
    }

    /**
     * 初始化布局
     */
    private void initView() {
        // 语音输入的布局
        lavVoiceInput = voiceLayout.findViewById(R.id.lavVoiceInput);
        lavVoiceInputsteptwo =  voiceLayout.findViewById(R.id.lavVoiceInputsteptwo);
        voiceBottomTip = voiceLayout.findViewById(R.id.dv_tv_bottom_tip);
        flVoiceInput = voiceLayout.findViewById(R.id.flVoiceInput);
        if(SpUtils.isNightMode()){
            //夜间模式
            lavVoiceInput.setAnimation("voice_input_night.json");
            lavVoiceInputsteptwo.setAnimation("voice_inputsteptwo_night.json");
        }else {
            lavVoiceInput.setAnimation("voice_input.json");
            lavVoiceInputsteptwo.setAnimation("voice_inputsteptwo.json");
        }
        lavVoiceInput.setRepeatCount(0);
        lavVoiceInputsteptwo.setRepeatCount(LottieDrawable.INFINITE);
        lavVoiceInput.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if(isstart){
                    isstart = false;
                    lavVoiceInput.pauseAnimation();
                    lavVoiceInputsteptwo.setVisibility(View.VISIBLE);
                    lavVoiceInputsteptwo.playAnimation();
                }

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    /**
     * 开始动画
     */
    private void startVoiceInputAnimation() {
        isstart = true;
        lavVoiceInputsteptwo.setVisibility(View.GONE);
        lavVoiceInputsteptwo.cancelAnimation();
        lavVoiceInputsteptwo.setProgress(0f);
        lavVoiceInput.playAnimation();
    }

    /**
     * 清除动画
     */
    private void stopVoiceInputAnimation() {
        isstart = false;
        lavVoiceInput.setVisibility(View.VISIBLE);
        lavVoiceInputsteptwo.setVisibility(View.GONE);
        lavVoiceInput.cancelAnimation();
        lavVoiceInput.setProgress(0f);
    }

    public void setMaxCountLength(int maxCountLength) {
        this.mMaxInputLength = maxCountLength;
        isLimit = true;
    }

    public void setChangeInputCountColor(@ColorRes int defaultColor, @ColorRes int changeColor) {
        isChangeInputCountColor = true;
        changeColors = new int[]{defaultColor, changeColor};
    }

    /**
     * 语音录制监听
     */
    @SuppressLint("ClickableViewAccessibility")
    private void addListener() {
        /*flVoiceInput.setOnClickListener(view -> {
            if (isRecording) {
                speechCompService.stopSpeech();
            } else {
                speechCompService.beginSpeech();
            }
        });*/

        flVoiceInput.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //长按输入
                if (!isRecording) {
                    speechCompService.beginSpeech();
                }
                return true;
            }
        });

        flVoiceInput.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    //松开停止
                    if (isRecording) {
                        speechCompService.stopSpeech();
                    }
                }
                return false;
            }
        });

        //输入框
        editText.addTextChangedListener(mEditInputListener);
        editText.setOnTouchListener((v, event) -> {
            if(useType == 1 && voiceSearchDialog != null){
                speechCompService.stopSpeech();
                KeyboardHelper.showSoftInput(editText);
                voiceSearchDialog.dismiss();
            }else {
                voicePressUpLift();
                voiceBottomTip.setText(ResUtils.getString(R.string.dialog_comment_long_an));
                showButton = 0;
                hideVoice();
                switchIcon();
            }
            return false;
        });

        //语音录入
        voiceBtn.setOnClickListener(v -> {
            if(useType == 1 && voiceSearchDialog != null){
                speechCompService.stopSpeech();
                KeyboardHelper.showSoftInput(editText);
                voiceSearchDialog.dismiss();
            }else {
                voicePressUpLift();
                checkPermission();
            }
        });


        // 语音输入监听
        speechCompService.setResultCallback(new SpeechResultCallback() {
            @Override
            public void start() {
                ThreadPoolUtils.postToMain(() -> {
                    Logger.t("ExpressionManager").d("识别开始");
                    isRecording = true;
                    voiceBottomTip.setText(R.string.dialog_comment_stop_tips);
                    startVoiceInputAnimation();
                });
            }

            @Override
            public void stop() {
                ThreadPoolUtils.postToMain(() -> {
                    voicePressUpLift();
                    if(StringUtils.isEmpty(editText.getText().toString())){
                        voiceBottomTip.setText(ResUtils.getString(R.string.str_no_voice_recognized_tips));
                    }else {
                        voiceBottomTip.setText(ResUtils.getString(R.string.dialog_comment_long_an));
                    }
                    Logger.t("ExpressionManager").d("识别暂停");
                });
            }

            @Override
            public void error() {
                ThreadPoolUtils.postToMain(() -> {
                    voicePressUpLift();
                    voiceBottomTip.setText(ResUtils.getString(R.string.str_no_voice_recognized_tips));
                });
            }

            @Override
            public void result(String result) {
                ThreadPoolUtils.postToMain(() -> {
                    appendString(result);
                    voicePressUpLift();
                    voiceBottomTip.setText(ResUtils.getString(R.string.dialog_comment_long_an));
                });
            }
        });

    }

    /**
     * 追加文字
     */
    private void appendString(String text) {
        int start = editText.getSelectionStart();
        int end = editText.getSelectionEnd();
        if (start == end) {
            editText.getEditableText().insert(start, text);
        } else {
            editText.getEditableText().replace(start, end, text);
        }
    }

    /**
     * 获取权限,保存图片
     */
    private void checkPermission() {
        PermissionsUtils.getRecordAudio(activity, new IPmsCallBack() {
            @Override
            public void granted() {
                clickVoice();
            }

            @Override
            public void notGranted() {
//                ToastNightUtil.showShort("没有权限或拒绝权限");
            }
        });
    }

    /**
     * 点击语音输入
     */
    private void clickVoice() {
        if (rootLayout == null) {

            if (isVoiceVisible()) {
                showButton = 0;
                switchIcon();
                hideVoice();
                KeyboardHelper.showSoftInput(editText);
            } else {
                showButton = 1;
                KeyboardHelper.hideSoftInput(editText);
                switchIcon();
                showVoice();
            }
        } else {
            if (showButton == 1) {
                showButton = 0;
                KeyboardHelper.showSoftInput(editText);
                switchIcon();
            } else if (showButton == 2) {
                showButton = 1;
                switchIcon();
                showVoice();
            } else {
                showButton = 1;
                if (rootLayout.getKeyBoardObservable().isKeyBoardVisibility()) {
                    switchIcon();
                    KeyboardHelper.hideSoftInput(editText);
                } else {
                    showVoice();
                    switchIcon();
                }
            }
        }
    }

    private void showVoice() {
        if (voiceLayout.getVisibility() == View.GONE) {
            voiceLayout.setVisibility(View.VISIBLE);
        }
    }

    private boolean isVoiceVisible() {
        return voiceLayout.getVisibility() == View.VISIBLE;
    }

    private void hideVoice() {
        if (voiceLayout.getVisibility() == View.VISIBLE) {
            voiceLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 切换按钮
     */
    public void switchIcon() {
        if (showButton == 1) {
            voiceBtn.setImageResource(R.drawable.ic_comment_select_keyboard);
        } else if (showButton == 2) {
            voiceBtn.setImageResource(R.drawable.ic_comment_sound_recording);
        } else {
            voiceBtn.setImageResource(R.drawable.ic_comment_sound_recording);
        }
    }

    /**
     * 停止动画
     */
    public void voicePressUpLift() {
        isRecording = false;
        stopVoiceInputAnimation();
    }

    private boolean isCutText = false;

    /**
     * 输入框监听
     */
    private final TextWatcher mEditInputListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!isLimit) {
                return;
            }

            // 判断一下,否则 超出最大值会截取,截取后重新赋值还会走这个方法
            if (isCutText) {
                isCutText = false;
                return;
            }

            String text = editText.getText().toString().trim();
            int length = 0;
            boolean isEmoji;
            for (int i = 0; i < text.length(); ) {
                isEmoji = false;
                if (!isEmojiCharacter(text.charAt(i))) {
                    i++;
                    length += 11;
                    isEmoji = true;
                }
                i++;
                length++;
                if (length > mMaxInputLength) {
                    ToastNightUtil.showShort("已达到输入上限");

                    isCutText = true;

                    int cutOutLength = i - 1;
                    if (isEmoji) {
                        cutOutLength = i - 2;
                    }
                    int endSelect = editText.getSelectionEnd();
                    String newStr = text.substring(0, cutOutLength);
                    editText.setText(newStr);
                    if (endSelect > cutOutLength) {
                        endSelect = cutOutLength;
                    }
                    editText.setSelection(endSelect);
                    break;
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

            if (inputTextListener != null) {
                inputTextListener.changed();
            }
        }
    };

    private InputTextListener inputTextListener;

    public void setInputTextListener(InputTextListener inputTextListener) {
        this.inputTextListener = inputTextListener;
    }

    /**
     * 监听输入变化
     */
    public interface InputTextListener {
        void changed();
    }

    private boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    @Override
    public void update(boolean keyBoardVisibility, int keyBoardHeight) {

    }

}