导航菜单

页面标题

页面副标题

夜猫麻将 v24.1.1 - TraeAudioManager.java 源代码

正在查看: 夜猫麻将 v24.1.1 应用的 TraeAudioManager.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.gme.sharpgme.jni;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import com.gme.av.ptt.PttError;
import com.gme.av.utils.ClientInfo;
import com.gme.av.utils.QLog;
import com.gme.sharpgme.jni.TraeMediaPlayer;
import com.unity3d.ads.metadata.MediationMetaData;
import com.unity3d.services.core.request.metrics.AdOperationMetric;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class TraeAudioManager extends BroadcastReceiver {
    public static final String ACTION_TRAEAUDIOMANAGER_NOTIFY = "com.gme.sharpgme.ACTION_TRAEAUDIOMANAGER_NOTIFY";
    public static final String ACTION_TRAEAUDIOMANAGER_REQUEST = "com.gme.sharpgme.ACTION_TRAEAUDIOMANAGER_REQUEST";
    public static final String ACTION_TRAEAUDIOMANAGER_RES = "com.gme.sharpgme.ACTION_TRAEAUDIOMANAGER_RES";
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_A2DP = 128;
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 256;
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 512;
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_SCO = 16;
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 64;
    static final int AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 32;
    static final int AUDIO_DEVICE_OUT_EARPIECE = 1;
    static final int AUDIO_DEVICE_OUT_SPEAKER = 2;
    static final int AUDIO_DEVICE_OUT_WIRED_HEADPHONE = 8;
    static final int AUDIO_DEVICE_OUT_WIRED_HEADSET = 4;
    public static final int AUDIO_MANAGER_ACTIVE_NONE = 0;
    public static final int AUDIO_MANAGER_ACTIVE_RING = 2;
    public static final int AUDIO_MANAGER_ACTIVE_VOICECALL = 1;
    static final String AUDIO_PARAMETER_STREAM_ROUTING = "routing";
    public static final String CONNECTDEVICE_DEVICENAME = "CONNECTDEVICE_DEVICENAME";
    public static final String CONNECTDEVICE_RESULT_DEVICENAME = "CONNECTDEVICE_RESULT_DEVICENAME";
    public static final String DEVICE_BLUETOOTHHEADSET = "DEVICE_BLUETOOTHHEADSET";
    public static final String DEVICE_EARPHONE = "DEVICE_EARPHONE";
    public static final String DEVICE_SPEAKERPHONE = "DEVICE_SPEAKERPHONE";
    public static final int DEVICE_STATUS_CONNECTED = 2;
    public static final int DEVICE_STATUS_CONNECTING = 1;
    public static final int DEVICE_STATUS_DISCONNECTED = 0;
    public static final int DEVICE_STATUS_DISCONNECTING = 3;
    public static final int DEVICE_STATUS_ERROR = -1;
    public static final int DEVICE_STATUS_UNCHANGEABLE = 4;
    public static final String DEVICE_WIREDHEADSET = "DEVICE_WIREDHEADSET";
    public static final int EARACTION_AWAY = 0;
    public static final int EARACTION_CLOSE = 1;
    public static final String EXTRA_DATA_AVAILABLEDEVICE_LIST = "EXTRA_DATA_AVAILABLEDEVICE_LIST";
    public static final String EXTRA_DATA_CONNECTEDDEVICE = "EXTRA_DATA_CONNECTEDDEVICE";
    public static final String EXTRA_DATA_DEVICECONFIG = "EXTRA_DATA_DEVICECONFIG";
    public static final String EXTRA_DATA_IF_HAS_BLUETOOTH_THIS_IS_NAME = "EXTRA_DATA_IF_HAS_BLUETOOTH_THIS_IS_NAME";
    public static final String EXTRA_DATA_PREV_CONNECTEDDEVICE = "EXTRA_DATA_PREV_CONNECTEDDEVICE";
    public static final String EXTRA_DATA_ROUTESWITCHEND_DEV = "EXTRA_DATA_ROUTESWITCHEND_DEV";
    public static final String EXTRA_DATA_ROUTESWITCHEND_TIME = "EXTRA_DATA_ROUTESWITCHEND_TIME";
    public static final String EXTRA_DATA_ROUTESWITCHSTART_FROM = "EXTRA_DATA_ROUTESWITCHSTART_FROM";
    public static final String EXTRA_DATA_ROUTESWITCHSTART_TO = "EXTRA_DATA_ROUTESWITCHSTART_TO";
    public static final String EXTRA_DATA_STREAMTYPE = "EXTRA_DATA_STREAMTYPE";
    public static final String EXTRA_EARACTION = "EXTRA_EARACTION";
    public static final int FORCE_ANALOG_DOCK = 8;
    public static final int FORCE_BT_A2DP = 4;
    public static final int FORCE_BT_CAR_DOCK = 6;
    public static final int FORCE_BT_DESK_DOCK = 7;
    public static final int FORCE_BT_SCO = 3;
    public static final int FORCE_DEFAULT = 0;
    public static final int FORCE_DIGITAL_DOCK = 9;
    public static final int FORCE_HEADPHONES = 2;
    public static final int FORCE_NONE = 0;
    public static final int FORCE_NO_BT_A2DP = 10;
    public static final int FORCE_SPEAKER = 1;
    public static final int FORCE_WIRED_ACCESSORY = 5;
    public static final int FOR_COMMUNICATION = 0;
    public static final int FOR_DOCK = 3;
    public static final int FOR_MEDIA = 1;
    public static final int FOR_RECORD = 2;
    public static final String GETCONNECTEDDEVICE_RESULT_LIST = "GETCONNECTEDDEVICE_REULT_LIST";
    public static final String GETCONNECTINGDEVICE_RESULT_LIST = "GETCONNECTINGDEVICE_REULT_LIST";
    public static final String ISDEVICECHANGABLED_RESULT_ISCHANGABLED = "ISDEVICECHANGABLED_REULT_ISCHANGABLED";
    public static final int MODE_GAME_PLAYBACK = 7;
    public static final int MODE_MUSIC_PLAYBACK = 2;
    public static final int MODE_MUSIC_PLAY_RECORD = 1;
    public static final int MODE_MUSIC_PLAY_RECORD_HIGH_QUALITY = 3;
    public static final int MODE_MUSIC_PLAY_RECORD_LOW_QUALITY = 5;
    public static final int MODE_VOICE_CHAT = 0;
    public static final int MODE_VOICE_PLAYBACK = 4;
    public static final String MUSIC_CONFIG = "DEVICE_SPEAKERPHONE;DEVICE_WIREDHEADSET;DEVICE_BLUETOOTHHEADSET;";
    public static final String NOTIFY_DEVICECHANGABLE_UPDATE = "NOTIFY_DEVICECHANGABLE_UPDATE";
    public static final String NOTIFY_DEVICECHANGABLE_UPDATE_DATE = "NOTIFY_DEVICECHANGABLE_UPDATE_DATE";
    public static final String NOTIFY_DEVICELIST_UPDATE = "NOTIFY_DEVICELISTUPDATE";
    public static final String NOTIFY_RING_COMPLETION = "NOTIFY_RING_COMPLETION";
    public static final String NOTIFY_ROUTESWITCHEND = "NOTIFY_ROUTESWITCHEND";
    public static final String NOTIFY_ROUTESWITCHSTART = "NOTIFY_ROUTESWITCHSTART";
    public static final String NOTIFY_SERVICE_STATE = "NOTIFY_SERVICE_STATE";
    public static final String NOTIFY_SERVICE_STATE_DATE = "NOTIFY_SERVICE_STATE_DATE";
    public static final String NOTIFY_STREAMTYPE_UPDATE = "NOTIFY_STREAMTYPE_UPDATE";
    private static final int NUM_FORCE_CONFIG = 11;
    private static final int NUM_FORCE_USE = 4;
    public static final String OPERATION_CONNECTDEVICE = "OPERATION_CONNECTDEVICE";
    public static final String OPERATION_CONNECT_HIGHEST_PRIORITY_DEVICE = "OPERATION_CONNECT_HIGHEST_PRIORITY_DEVICE";
    public static final String OPERATION_EARACTION = "OPERATION_EARACTION";
    public static final String OPERATION_FORCE_CONNECTDEVICE = "OPERATION_FORCE_CONNECTDEVICE";
    public static final String OPERATION_GETCONNECTEDDEVICE = "OPERATION_GETCONNECTEDDEVICE";
    public static final String OPERATION_GETCONNECTINGDEVICE = "OPERATION_GETCONNECTINGDEVICE";
    public static final String OPERATION_GETDEVICELIST = "OPERATION_GETDEVICELIST";
    public static final String OPERATION_GETSTREAMTYPE = "OPERATION_GETSTREAMTYPE";
    public static final String OPERATION_ISDEVICECHANGABLED = "OPERATION_ISDEVICECHANGABLED";
    public static final String OPERATION_RECOVER_AUDIO_FOCUS = "OPERATION_RECOVER_AUDIO_FOCUS";
    public static final String OPERATION_REGISTERAUDIOSESSION = "OPERATION_REGISTERAUDIOSESSION";
    public static final String OPERATION_REQUEST_RELEASE_AUDIO_FOCUS = "OPERATION_REQUEST_RELEASE_AUDIO_FOCUS";
    public static final String OPERATION_STARTRING = "OPERATION_STARTRING";
    public static final String OPERATION_STARTSERVICE = "OPERATION_STARTSERVICE";
    public static final String OPERATION_STOPRING = "OPERATION_STOPRING";
    public static final String OPERATION_STOPSERVICE = "OPERATION_STOPSERVICE";
    public static final String OPERATION_VOICECALL_AUDIOPARAM_CHANGED = "OPERATION_VOICECALL_AUDIOPARAM_CHANGED";
    public static final String OPERATION_VOICECALL_POSTPROCESS = "OPERATION_VOICECALL_POSTROCESS";
    public static final String OPERATION_VOICECALL_PREPROCESS = "OPERATION_VOICECALL_PREPROCESS";
    public static final String PARAM_DEVICE = "PARAM_DEVICE";
    public static final String PARAM_ERROR = "PARAM_ERROR";
    public static final String PARAM_ISHOSTSIDE = "PARAM_ISHOSTSIDE";
    public static final String PARAM_MODEPOLICY = "PARAM_MODEPOLICY";
    public static final String PARAM_OPERATION = "PARAM_OPERATION";
    public static final String PARAM_RES_ERRCODE = "PARAM_RES_ERRCODE";
    public static final String PARAM_RING_DATASOURCE = "PARAM_RING_DATASOURCE";
    public static final String PARAM_RING_FILEPATH = "PARAM_RING_FILEPATH";
    public static final String PARAM_RING_LOOP = "PARAM_RING_LOOP";
    public static final String PARAM_RING_LOOPCOUNT = "PARAM_RING_LOOPCOUNT";
    public static final String PARAM_RING_MODE = "PARAM_RING_MODE";
    public static final String PARAM_RING_RSID = "PARAM_RING_RSID";
    public static final String PARAM_RING_URI = "PARAM_RING_URI";
    public static final String PARAM_RING_USERDATA_STRING = "PARAM_RING_USERDATA_STRING";
    public static final String PARAM_SESSIONID = "PARAM_SESSIONID";
    public static final String PARAM_STATUS = "PARAM_STATUS";
    public static final String PARAM_STREAMTYPE = "PARAM_STREAMTYPE";
    public static final String REGISTERAUDIOSESSION_ISREGISTER = "REGISTERAUDIOSESSION_ISREGISTER";
    public static final int RES_ERRCODE_DEVICE_BTCONNCECTED_TIMEOUT = 10;
    public static final int RES_ERRCODE_DEVICE_NOT_VISIABLE = 8;
    public static final int RES_ERRCODE_DEVICE_UNCHANGEABLE = 9;
    public static final int RES_ERRCODE_DEVICE_UNKOWN = 7;
    public static final int RES_ERRCODE_NONE = 0;
    public static final int RES_ERRCODE_RING_NOT_EXIST = 5;
    public static final int RES_ERRCODE_SERVICE_OFF = 1;
    public static final int RES_ERRCODE_STOPRING_INTERRUPT = 4;
    public static final int RES_ERRCODE_VOICECALLPOST_INTERRUPT = 6;
    public static final int RES_ERRCODE_VOICECALL_EXIST = 2;
    public static final int RES_ERRCODE_VOICECALL_NOT_EXIST = 3;
    private static final String TAG = "TraeAudioManager";
    public static final String VIDEO_CONFIG = "DEVICE_EARPHONE;DEVICE_SPEAKERPHONE;DEVICE_BLUETOOTHHEADSET;DEVICE_WIREDHEADSET;";
    public static final String VOICECALL_CONFIG = "DEVICE_SPEAKERPHONE;DEVICE_EARPHONE;DEVICE_BLUETOOTHHEADSET;DEVICE_WIREDHEADSET;";
    Context _context;
    TraeAudioManagerLooper mTraeAudioManagerLooper;
    public static boolean IsMusicScene = false;
    public static int nSceneMode = -1;
    public static int nSpecialModeBypass3A = 0;
    public static int nSpeakerStreamType = 0;
    public static boolean IsEarPhoneSupported = false;
    public static boolean IsUpdateSceneFlag = false;
    public static final String DEVICE_NONE = "DEVICE_NONE";
    public static String CurConnectedDevice = DEVICE_NONE;
    static ReentrantLock _glock = new ReentrantLock();
    static TraeAudioManager _ginstance = null;
    static int _gHostProcessId = -1;
    static final String[] forceName = {"FORCE_NONE", "FORCE_SPEAKER", "FORCE_HEADPHONES", "FORCE_BT_SCO", "FORCE_BT_A2DP", "FORCE_WIRED_ACCESSORY", "FORCE_BT_CAR_DOCK", "FORCE_BT_DESK_DOCK", "FORCE_ANALOG_DOCK", "FORCE_NO_BT_A2DP", "FORCE_DIGITAL_DOCK"};
    AudioManager _am = null;
    boolean _speakerOn = true;
    int _activeMode = 0;
    int _prevMode = 0;
    int _streamType = 0;
    int _modePolicy = -1;
    private int bluetoothState = 4;
    boolean IsBluetoothA2dpExisted = true;
    TraeAudioSessionHost _audioSessionHost = null;
    DeviceConfigManager _deviceConfigManager = null;
    BluetoohHeadsetCheckInterface _bluetoothCheck = null;
    String sessionConnectedDev = DEVICE_NONE;
    ReentrantLock _lock = new ReentrantLock();
    switchThread _switchThread = null;

    public interface Bluetooth_State {
        public static final int ERROR = 2;
        public static final int HEADSET_AVAILABLE = 4;
        public static final int HEADSET_UNAVAILABLE = 3;
        public static final int SCO_CONNECTED = 7;
        public static final int SCO_CONNECTING = 6;
        public static final int SCO_DISCONNECTING = 5;
        public static final int UNINITIALIZED = 1;
    }

    public class Parameters {
        public static final String BLUETOOTHPOLICY = "com.gme.sharpgme.TraeAudioManager.Parameters.BLUETOOTHPOLICY";
        public static final String CONTEXT = "com.gme.sharpgme.TraeAudioManager.Parameters.CONTEXT";
        public static final String DEVICECONFIG = "com.gme.sharpgme.TraeAudioManager.Parameters.DEVICECONFIG";
        public static final String MODEPOLICY = "com.gme.sharpgme.TraeAudioManager.Parameters.MODEPOLICY";

        public Parameters() {
        }
    }

    public static String getConnectedDevice() {
        return CurConnectedDevice;
    }

    public static boolean checkDevName(String strDeviceName) {
        if (strDeviceName == null) {
            return false;
        }
        if (!DEVICE_SPEAKERPHONE.equals(strDeviceName) && !DEVICE_EARPHONE.equals(strDeviceName) && !DEVICE_WIREDHEADSET.equals(strDeviceName) && !DEVICE_BLUETOOTHHEADSET.equals(strDeviceName)) {
            return false;
        }
        return true;
    }

    public static boolean isHandfree(String strDeviceName) {
        return checkDevName(strDeviceName) && DEVICE_SPEAKERPHONE.equals(strDeviceName);
    }

    class DeviceConfigManager {
        HashMap<String, DeviceConfig> deviceConfigs = new HashMap<>();
        String prevConnectedDevice = TraeAudioManager.DEVICE_NONE;
        String connectedDevice = TraeAudioManager.DEVICE_NONE;
        String connectingDevice = TraeAudioManager.DEVICE_NONE;
        ReentrantLock mLock = new ReentrantLock();
        boolean visiableUpdate = false;
        String _bluetoothDevName = "unknow";

        public class DeviceConfig {
            String deviceName = TraeAudioManager.DEVICE_NONE;
            boolean visible = false;
            int priority = 0;

            public DeviceConfig() {
            }

            public boolean init(String strDeviceName, int nPriority) {
                if (strDeviceName == null || strDeviceName.length() <= 0 || !TraeAudioManager.checkDevName(strDeviceName)) {
                    return false;
                }
                this.deviceName = strDeviceName;
                this.priority = nPriority;
                return true;
            }

            public String getDeviceName() {
                return this.deviceName;
            }

            public boolean getVisible() {
                return this.visible;
            }

            public int getPriority() {
                return this.priority;
            }

            public void setVisible(boolean arg) {
                this.visible = arg;
            }
        }

        public DeviceConfigManager() {
        }

        public boolean init(String strConfigs) {
            String strConfigs2;
            AudioDeviceInterface.LogTraceEntry(" strConfigs:" + strConfigs);
            if (strConfigs == null || strConfigs.length() <= 0 || (strConfigs2 = strConfigs.replace("\n", "").replace("\r", "")) == null || strConfigs2.length() <= 0) {
                return false;
            }
            if (strConfigs2.indexOf(";") < 0) {
                strConfigs2 = strConfigs2 + ";";
            }
            String[] configs = strConfigs2.split(";");
            if (configs == null || 1 > configs.length) {
                return false;
            }
            this.mLock.lock();
            for (int i = 0; i < configs.length; i++) {
                _addConfig(configs[i], i);
            }
            this.mLock.unlock();
            TraeAudioManager.this.printDevices();
            return true;
        }

        boolean _addConfig(String strDeviceName, int nPriority) {
            AudioDeviceInterface.LogTraceEntry(" devName:" + strDeviceName + " priority:" + nPriority);
            DeviceConfig dc = new DeviceConfig();
            if (dc.init(strDeviceName, nPriority)) {
                if (this.deviceConfigs.containsKey(strDeviceName)) {
                    QLog.e(TraeAudioManager.TAG, "err dev exist!");
                    return false;
                }
                this.deviceConfigs.put(strDeviceName, dc);
                this.visiableUpdate = true;
                QLog.w(TraeAudioManager.TAG, " n" + getDeviceNumber() + " 0:" + getDeviceName(0));
                AudioDeviceInterface.LogTraceExit();
                return true;
            }
            QLog.e(TraeAudioManager.TAG, " err dev init!");
            return false;
        }

        public void clearConfig() {
            this.mLock.lock();
            this.deviceConfigs.clear();
            this.prevConnectedDevice = TraeAudioManager.DEVICE_NONE;
            this.connectedDevice = TraeAudioManager.DEVICE_NONE;
            TraeAudioManager.CurConnectedDevice = TraeAudioManager.DEVICE_NONE;
            this.connectingDevice = TraeAudioManager.DEVICE_NONE;
            this.mLock.unlock();
        }

        public boolean getVisiableUpdateFlag() {
            this.mLock.lock();
            boolean res = this.visiableUpdate;
            this.mLock.unlock();
            return res;
        }

        public void resetVisiableUpdateFlag() {
            this.mLock.lock();
            this.visiableUpdate = false;
            this.mLock.unlock();
        }

        public boolean setVisible(String strDeviceName, boolean bVisible) {
            boolean bRet = false;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null && dc.getVisible() != bVisible) {
                dc.setVisible(bVisible);
                this.visiableUpdate = true;
                StringBuilder sb = new StringBuilder();
                sb.append(" ++setVisible:");
                sb.append(strDeviceName);
                sb.append(bVisible ? " Y" : " N");
                QLog.w(TraeAudioManager.TAG, sb.toString());
                bRet = true;
            }
            this.mLock.unlock();
            return bRet;
        }

        public void setBluetoothName(String btName) {
            if (btName == null) {
                this._bluetoothDevName = "unknow";
            } else if (btName.isEmpty()) {
                this._bluetoothDevName = "unknow";
            } else {
                this._bluetoothDevName = btName;
            }
        }

        public String getBluetoothName() {
            return this._bluetoothDevName;
        }

        public boolean getVisible(String strDeviceName) {
            boolean bRet = false;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null) {
                bRet = dc.getVisible();
            }
            this.mLock.unlock();
            return bRet;
        }

        public int getPriority(String strDeviceName) {
            int nRet = -1;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null) {
                nRet = dc.getPriority();
            }
            this.mLock.unlock();
            return nRet;
        }

        public int getDeviceNumber() {
            this.mLock.lock();
            int n = this.deviceConfigs.size();
            this.mLock.unlock();
            return n;
        }

        public String getDeviceName(int id) {
            String str = TraeAudioManager.DEVICE_NONE;
            int i = 0;
            this.mLock.lock();
            DeviceConfig _dc = null;
            Iterator iter = this.deviceConfigs.entrySet().iterator();
            while (true) {
                if (!iter.hasNext()) {
                    break;
                }
                Map.Entry<String, DeviceConfig> entry = iter.next();
                if (i == id) {
                    DeviceConfig _dc2 = entry.getValue();
                    _dc = _dc2;
                    break;
                }
                i++;
            }
            if (_dc != null) {
                str = _dc.getDeviceName();
            }
            this.mLock.unlock();
            return str;
        }

        public String getAvailabledHighestPriorityDevice(String IgnoreDeviceName) {
            DeviceConfig dst = null;
            this.mLock.lock();
            for (Map.Entry<String, DeviceConfig> entry : this.deviceConfigs.entrySet()) {
                entry.getKey();
                entry.getValue();
                DeviceConfig _dc = entry.getValue();
                if (_dc != null && _dc.getVisible() && !_dc.getDeviceName().equals(IgnoreDeviceName)) {
                    if (dst == null) {
                        dst = _dc;
                    } else if (_dc.getPriority() >= dst.getPriority()) {
                        dst = _dc;
                    }
                }
            }
            this.mLock.unlock();
            return dst != null ? dst.getDeviceName() : TraeAudioManager.DEVICE_SPEAKERPHONE;
        }

        public String getAvailabledHighestPriorityDevice() {
            DeviceConfig dst = null;
            this.mLock.lock();
            for (Map.Entry<String, DeviceConfig> entry : this.deviceConfigs.entrySet()) {
                entry.getKey();
                entry.getValue();
                DeviceConfig _dc = entry.getValue();
                if (_dc != null && _dc.getVisible()) {
                    if (dst == null) {
                        dst = _dc;
                    } else if (_dc.getPriority() >= dst.getPriority()) {
                        dst = _dc;
                    }
                }
            }
            this.mLock.unlock();
            return dst != null ? dst.getDeviceName() : TraeAudioManager.DEVICE_SPEAKERPHONE;
        }

        public String getConnectingDevice() {
            this.mLock.lock();
            String str = null;
            DeviceConfig dc = this.deviceConfigs.get(this.connectingDevice);
            if (dc != null && dc.getVisible()) {
                str = this.connectingDevice;
            }
            this.mLock.unlock();
            return str;
        }

        public String getConnectedDevice() {
            this.mLock.lock();
            String str = _getConnectedDevice();
            this.mLock.unlock();
            return str;
        }

        public String getPrevConnectedDevice() {
            this.mLock.lock();
            String str = _getPrevConnectedDevice();
            this.mLock.unlock();
            return str;
        }

        public boolean setConnecting(String strDeviceName) {
            boolean res = false;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null && dc.getVisible()) {
                this.connectingDevice = strDeviceName;
                res = true;
            }
            this.mLock.unlock();
            return res;
        }

        public boolean setConnected(String strDeviceName) {
            boolean res = false;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null && dc.getVisible()) {
                String str = this.connectedDevice;
                if (str != null && !str.equals(strDeviceName)) {
                    this.prevConnectedDevice = this.connectedDevice;
                }
                this.connectedDevice = strDeviceName;
                TraeAudioManager.CurConnectedDevice = strDeviceName;
                this.connectingDevice = "";
                res = true;
            }
            this.mLock.unlock();
            return res;
        }

        public boolean isConnected(String strDeviceName) {
            boolean res = false;
            this.mLock.lock();
            DeviceConfig dc = this.deviceConfigs.get(strDeviceName);
            if (dc != null && dc.getVisible()) {
                res = this.connectedDevice.equals(strDeviceName);
            }
            this.mLock.unlock();
            return res;
        }

        public HashMap<String, Object> getSnapParams() {
            HashMap<String, Object> params = new HashMap<>();
            this.mLock.lock();
            params.put(TraeAudioManager.EXTRA_DATA_AVAILABLEDEVICE_LIST, _getAvailableDeviceList());
            params.put(TraeAudioManager.EXTRA_DATA_CONNECTEDDEVICE, _getConnectedDevice());
            params.put(TraeAudioManager.EXTRA_DATA_PREV_CONNECTEDDEVICE, _getPrevConnectedDevice());
            this.mLock.unlock();
            return params;
        }

        public ArrayList<String> getAvailableDeviceList() {
            new ArrayList();
            this.mLock.lock();
            ArrayList<String> list = _getAvailableDeviceList();
            this.mLock.unlock();
            return list;
        }

        ArrayList<String> _getAvailableDeviceList() {
            ArrayList<String> list = new ArrayList<>();
            for (Map.Entry<String, DeviceConfig> entry : this.deviceConfigs.entrySet()) {
                DeviceConfig _dc = entry.getValue();
                if (_dc != null && _dc.getVisible()) {
                    list.add(_dc.getDeviceName());
                }
            }
            return list;
        }

        String _getConnectedDevice() {
            DeviceConfig dc = this.deviceConfigs.get(this.connectedDevice);
            if (dc == null || !dc.getVisible()) {
                return TraeAudioManager.DEVICE_NONE;
            }
            String str = this.connectedDevice;
            return str;
        }

        String _getPrevConnectedDevice() {
            DeviceConfig dc = this.deviceConfigs.get(this.prevConnectedDevice);
            if (dc == null || !dc.getVisible()) {
                return TraeAudioManager.DEVICE_NONE;
            }
            String str = this.prevConnectedDevice;
            return str;
        }
    }

    void printDevices() {
        AudioDeviceInterface.LogTraceEntry("");
        int n = this._deviceConfigManager.getDeviceNumber();
        QLog.w(TAG, "   ConnectedDevice:" + this._deviceConfigManager.getConnectedDevice());
        QLog.w(TAG, "   ConnectingDevice:" + this._deviceConfigManager.getConnectingDevice());
        QLog.w(TAG, "   prevConnectedDevice:" + this._deviceConfigManager.getPrevConnectedDevice());
        QLog.w(TAG, "   AHPDevice:" + this._deviceConfigManager.getAvailabledHighestPriorityDevice());
        QLog.w(TAG, "   deviceNamber:" + n);
        for (int i = 0; i < n; i++) {
            String devName = this._deviceConfigManager.getDeviceName(i);
            QLog.w(TAG, "      " + i + " devName:" + devName + " Visible:" + this._deviceConfigManager.getVisible(devName) + " Priority:" + this._deviceConfigManager.getPriority(devName));
        }
        String[] alist = (String[]) this._deviceConfigManager.getAvailableDeviceList().toArray(new String[0]);
        QLog.w(TAG, "   AvailableNamber:" + alist.length);
        for (int i2 = 0; i2 < alist.length; i2++) {
            String devName2 = alist[i2];
            QLog.w(TAG, "      " + i2 + " devName:" + devName2 + " Visible:" + this._deviceConfigManager.getVisible(devName2) + " Priority:" + this._deviceConfigManager.getPriority(devName2));
        }
        AudioDeviceInterface.LogTraceExit();
    }

    static boolean isCloseSystemAPM(int modePolicy) {
        if (modePolicy != -1) {
            return false;
        }
        if (ClientInfo.MANUFACTURER.equals("Xiaomi")) {
            if (ClientInfo.MODEL.equals("MI 2") || ClientInfo.MODEL.equals("MI 2A") || ClientInfo.MODEL.equals("MI 2S") || ClientInfo.MODEL.equals("MI 2SC")) {
                return true;
            }
        } else if (ClientInfo.MANUFACTURER.equals("samsung") && ClientInfo.MODEL.equals("SCH-I959")) {
            return true;
        }
        return false;
    }

    static int getAudioSource(int audioSourcePolicy) {
        int source = 0;
        if (IsMusicScene) {
            return 0;
        }
        int apiLevel = ClientInfo.VERSION_SDK_INT;
        if (audioSourcePolicy >= 0) {
            QLog.w(TAG, "[Config] getAudioSource _audioSourcePolicy:" + audioSourcePolicy + " source:" + audioSourcePolicy);
            return audioSourcePolicy;
        }
        if (apiLevel >= 11) {
            source = 7;
        }
        QLog.w(TAG, "[Config] getAudioSource _audioSourcePolicy:" + audioSourcePolicy + " source:" + source);
        return source;
    }

    static int getAudioStreamType(int audioStreamTypePolicy) {
        int streamType = 3;
        if (IsMusicScene) {
            return 3;
        }
        int apiLevel = ClientInfo.VERSION_SDK_INT;
        if (audioStreamTypePolicy >= 0) {
            streamType = audioStreamTypePolicy;
        } else if (apiLevel >= 9) {
            streamType = 0;
        }
        QLog.w(TAG, "[Config] getAudioStreamType audioStreamTypePolicy:" + audioStreamTypePolicy + " streamType:" + streamType);
        return streamType;
    }

    static int getCallAudioMode(int modePolicy) {
        int mode = 0;
        if (IsMusicScene) {
            return 0;
        }
        int apiLevel = ClientInfo.VERSION_SDK_INT;
        if (modePolicy >= 0) {
            QLog.w(TAG, "[Config] getCallAudioMode modePolicy:" + modePolicy + " mode:" + modePolicy);
            return modePolicy;
        }
        if (apiLevel >= 11) {
            mode = 3;
        }
        QLog.w(TAG, "[Config] getCallAudioMode _modePolicy:" + modePolicy + " mode:" + mode + "facturer:" + ClientInfo.MANUFACTURER + " model:" + ClientInfo.MODEL);
        return mode;
    }

    void updateDeviceStatus() {
        int n = this._deviceConfigManager.getDeviceNumber();
        for (int i = 0; i < n; i++) {
            boolean setSuccess = false;
            String devName = this._deviceConfigManager.getDeviceName(i);
            if (devName != null) {
                if (devName.equals(DEVICE_BLUETOOTHHEADSET)) {
                    BluetoohHeadsetCheckInterface bluetoohHeadsetCheckInterface = this._bluetoothCheck;
                    setSuccess = bluetoohHeadsetCheckInterface == null ? this._deviceConfigManager.setVisible(devName, false) : this._deviceConfigManager.setVisible(devName, bluetoohHeadsetCheckInterface.isConnected());
                } else if (devName.equals(DEVICE_WIREDHEADSET)) {
                    setSuccess = this._deviceConfigManager.setVisible(devName, this._am.isWiredHeadsetOn());
                } else if (devName.equals(DEVICE_SPEAKERPHONE)) {
                    this._deviceConfigManager.setVisible(devName, true);
                }
            }
            if (setSuccess) {
                QLog.w(TAG, "pollUpdateDevice dev:" + devName + " Visible:" + this._deviceConfigManager.getVisible(devName));
            }
        }
        checkAutoDeviceListUpdate();
    }

    void _updateEarphoneVisable() {
        if (this._deviceConfigManager.getVisible(DEVICE_WIREDHEADSET)) {
            QLog.w(TAG, " detected headset plugin,so disable earphone");
            this._deviceConfigManager.setVisible(DEVICE_EARPHONE, false);
        } else {
            QLog.w(TAG, " detected headset plugout,so enable earphone");
            this._deviceConfigManager.setVisible(DEVICE_EARPHONE, true);
        }
    }

    void checkAutoDeviceListUpdate() {
        if (this._deviceConfigManager.getVisiableUpdateFlag()) {
            QLog.w(TAG, "checkAutoDeviceListUpdate got update!");
            _updateEarphoneVisable();
            this._deviceConfigManager.resetVisiableUpdateFlag();
            HashMap<String, Object> params = new HashMap<>();
            internalSendMessage(32785, params);
        }
    }

    void checkDevicePlug(String devName, boolean isPlugin) {
        if (this._deviceConfigManager.getVisiableUpdateFlag()) {
            StringBuilder sb = new StringBuilder();
            sb.append("checkDevicePlug got update dev:");
            sb.append(devName);
            sb.append(isPlugin ? " piugin" : " plugout");
            sb.append(" connectedDev:");
            sb.append(this._deviceConfigManager.getConnectedDevice());
            QLog.w(TAG, sb.toString());
            _updateEarphoneVisable();
            this._deviceConfigManager.resetVisiableUpdateFlag();
            if (isPlugin) {
                HashMap<String, Object> params = new HashMap<>();
                params.put(PARAM_DEVICE, devName);
                internalSendMessage(32786, params);
                return;
            }
            String connectedDev = this._deviceConfigManager.getConnectedDevice();
            if (connectedDev.equals(devName) || connectedDev.equals(DEVICE_NONE)) {
                HashMap<String, Object> params2 = new HashMap<>();
                params2.put(PARAM_DEVICE, devName);
                internalSendMessage(32787, params2);
                return;
            }
            QLog.w(TAG, " ---No switch,plugout:" + devName + " connectedDev:" + connectedDev);
            internalSendMessage(32785, new HashMap<>());
        }
    }

    class TraeAudioManagerLooper extends Thread {
        public static final int MESSAGE_AUTO_DEVICELIST_PLUGIN_UPDATE = 32786;
        public static final int MESSAGE_AUTO_DEVICELIST_PLUGOUT_UPDATE = 32787;
        public static final int MESSAGE_AUTO_DEVICELIST_UPDATE = 32785;
        public static final int MESSAGE_BEGIN = 32768;
        public static final int MESSAGE_CONNECTDEVICE = 32775;
        public static final int MESSAGE_CONNECT_HIGHEST_PRIORITY_DEVICE = 32789;
        public static final int MESSAGE_DISABLE = 32773;
        public static final int MESSAGE_EARACTION = 32776;
        public static final int MESSAGE_ENABLE = 32772;
        public static final int MESSAGE_FORCE_CONNECTDEVICE = 32792;
        public static final int MESSAGE_GETCONNECTEDDEVICE = 32778;
        public static final int MESSAGE_GETCONNECTINGDEVICE = 32779;
        public static final int MESSAGE_GETDEVICELIST = 32774;
        public static final int MESSAGE_GETSTREAMTYPE = 32784;
        public static final int MESSAGE_ISDEVICECHANGABLED = 32777;
        public static final int MESSAGE_RECOVER_AUDIO_FOCUS = 32791;
        public static final int MESSAGE_REQUEST_RELEASE_AUDIO_FOCUS = 32790;
        public static final int MESSAGE_STARTRING = 32782;
        public static final int MESSAGE_STOPRING = 32783;
        public static final int MESSAGE_VOICECALLPOSTPROCESS = 32781;
        public static final int MESSAGE_VOICECALLPREPROCESS = 32780;
        public static final int MESSAGE_VOICECALL_AUIDOPARAM_CHANGED = 32788;
        TraeAudioManager _parent;
        Handler mMsgHandler = null;
        TraeMediaPlayer _ringPlayer = null;
        long _ringSessionID = -1;
        String _ringOperation = "";
        String _ringUserdata = "";
        final boolean[] _started = {false};
        boolean _enabled = false;
        String _lastCfg = "";
        int _preServiceMode = 0;
        int _preRingMode = 0;
        boolean IsFirstConnectDeviceFlag = true;
        long _voiceCallSessionID = -1;
        String _voiceCallOperation = "";
        AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = null;
        int _focusSteamType = 0;

        public TraeAudioManagerLooper(TraeAudioManager parent) {
            this._parent = null;
            this._parent = parent;
            long lasttime = SystemClock.elapsedRealtime();
            QLog.e(TraeAudioManager.TAG, "TraeAudioManagerLooper start...");
            start();
            synchronized (this._started) {
                if (!this._started[0]) {
                    try {
                        this._started.wait(3000L);
                    } catch (InterruptedException e) {
                    }
                }
            }
            QLog.e(TraeAudioManager.TAG, "  start used:" + (SystemClock.elapsedRealtime() - lasttime) + "ms");
        }

        public void quit() {
            AudioDeviceInterface.LogTraceEntry("");
            if (this.mMsgHandler == null) {
                return;
            }
            long lasttime = SystemClock.elapsedRealtime();
            this.mMsgHandler.getLooper().quit();
            synchronized (this._started) {
                if (this._started[0]) {
                    try {
                        this._started.wait(10000L);
                    } catch (InterruptedException e) {
                    }
                }
            }
            QLog.e(TraeAudioManager.TAG, "  quit used:" + (SystemClock.elapsedRealtime() - lasttime) + "ms");
            this.mMsgHandler = null;
            AudioDeviceInterface.LogTraceExit();
        }

        public int sendMessage(int nMsg, HashMap<String, Object> params) {
            Handler handler = this.mMsgHandler;
            if (handler == null) {
                StringBuilder sb = new StringBuilder();
                sb.append(" fail mMsgHandler==null _enabled:");
                sb.append(this._enabled ? "Y" : "N");
                sb.append(" activeMode:");
                sb.append(TraeAudioManager.this._activeMode);
                sb.append(" msg:");
                sb.append(nMsg);
                AudioDeviceInterface.LogTraceEntry(sb.toString());
                return -1;
            }
            Message msg = Message.obtain(handler, nMsg, params);
            return this.mMsgHandler.sendMessage(msg) ? 0 : -1;
        }

        void startService(HashMap<String, Object> params) {
            String strCfg = (String) params.get(TraeAudioManager.EXTRA_DATA_DEVICECONFIG);
            Log.w(TraeAudioManager.TAG, "startService cfg:" + strCfg);
            StringBuilder sb = new StringBuilder();
            sb.append(" _enabled:");
            sb.append(this._enabled ? "Y" : "N");
            sb.append(" activeMode:");
            sb.append(TraeAudioManager.this._activeMode);
            sb.append(" cfg:");
            sb.append(strCfg);
            AudioDeviceInterface.LogTraceEntry(sb.toString());
            if (TraeAudioManager.this._context == null) {
                return;
            }
            if (strCfg.equals("resume service")) {
                strCfg = this._lastCfg;
            }
            QLog.w(TraeAudioManager.TAG, "   startService:" + strCfg);
            if ((this._enabled && this._lastCfg.equals(strCfg)) || TraeAudioManager.this._activeMode != 0) {
                return;
            }
            if (this._enabled) {
                stopService();
            }
            _prev_startService();
            TraeAudioManager.this._deviceConfigManager.clearConfig();
            TraeAudioManager.this._deviceConfigManager.init(strCfg);
            this._lastCfg = strCfg;
            if (TraeAudioManager.this._am != null) {
                this._preServiceMode = TraeAudioManager.this._am.getMode();
            }
            this._enabled = true;
            if (this._ringPlayer == null) {
                this._ringPlayer = new TraeMediaPlayer(TraeAudioManager.this._context, new TraeMediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion() {
                        QLog.w(TraeAudioManager.TAG, "_ringPlayer onCompletion _activeMode:" + TraeAudioManager.this._activeMode + " _preRingMode:" + TraeAudioManagerLooper.this._preRingMode);
                        HashMap<String, Object> params2 = new HashMap<>();
                        params2.put(TraeAudioManager.PARAM_ISHOSTSIDE, true);
                        TraeAudioManagerLooper.this.sendMessage(TraeAudioManagerLooper.MESSAGE_STOPRING, params2);
                        TraeAudioManagerLooper.this.notifyRingCompletion();
                    }
                });
            }
            notifyServiceState(this._enabled);
            TraeAudioManager.this.updateDeviceStatus();
            AudioDeviceInterface.LogTraceExit();
        }

        boolean isNeedForceVolumeType() {
            if (ClientInfo.MANUFACTURER.equals("Xiaomi")) {
                return ClientInfo.MODEL.equals("MI 5") || ClientInfo.MODEL.equals("MI 5s") || ClientInfo.MODEL.equals("MI 5s Plus");
            }
            return false;
        }

        void stopService() {
            StringBuilder sb = new StringBuilder();
            sb.append(" _enabled:");
            sb.append(this._enabled ? "Y" : "N");
            sb.append(" activeMode:");
            sb.append(TraeAudioManager.this._activeMode);
            AudioDeviceInterface.LogTraceEntry(sb.toString());
            if (!this._enabled) {
                return;
            }
            if (TraeAudioManager.this._activeMode == 1) {
                interruptVoicecallPostprocess();
            } else if (TraeAudioManager.this._activeMode == 2) {
                interruptRing();
            }
            if (TraeAudioManager.this._switchThread != null) {
                QLog.w(TraeAudioManager.TAG, "_switchThread:" + TraeAudioManager.this._switchThread.getDeviceName());
                TraeAudioManager.this._switchThread.quit();
                TraeAudioManager.this._switchThread = null;
            }
            TraeMediaPlayer traeMediaPlayer = this._ringPlayer;
            if (traeMediaPlayer != null) {
                traeMediaPlayer.stopRing();
            }
            this._ringPlayer = null;
            this._enabled = false;
            notifyServiceState(false);
            if (TraeAudioManager.this._am != null && TraeAudioManager.this._context != null) {
                try {
                    TraeAudioManager.this.InternalSetMode(0);
                    QLog.w(TraeAudioManager.TAG, "forceVolumeControlStream: -1");
                    TraeAudioManager.forceVolumeControlStream(TraeAudioManager.this._am, -1);
                } catch (Exception e) {
                }
            }
            _post_stopService();
            AudioDeviceInterface.LogTraceExit();
        }

        int notifyServiceState(boolean on) {
            if (TraeAudioManager.this._context == null) {
                return -1;
            }
            Intent intent = new Intent();
            intent.setAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_NOTIFY);
            intent.putExtra(TraeAudioManager.PARAM_OPERATION, TraeAudioManager.NOTIFY_SERVICE_STATE);
            intent.putExtra(TraeAudioManager.NOTIFY_SERVICE_STATE_DATE, on);
            if (TraeAudioManager.this._context != null) {
                TraeAudioManager.this._context.sendBroadcast(intent);
                return 0;
            }
            return 0;
        }

        String msgToText(int what) {
            switch (what) {
                case 32768:
                    return "MESSAGE_BEGIN";
                case PttError.VOICE_V2T_INTERNAL_ERROR:
                    return "MESSAGE_SETWIREDHEADSET";
                case PttError.VOICE_V2T_NETWORK_FAIL:
                    return "MESSAGE_SETBLUETOOTHHEADSET";
                case 32771:
                    return "MESSAGE_SETDEVICECONFIG";
                case 32772:
                    return "MESSAGE_ENABLE";
                case MESSAGE_DISABLE:
                    return "MESSAGE_DISABLE";
                case 32774:
                    return "MESSAGE_GETDEVICELIST";
                case 32775:
                    return "MESSAGE_CONNECTDEVICE";
                case 32776:
                    return "MESSAGE_EARACTION";
                case 32777:
                    return "MESSAGE_ISDEVICECHANGABLED";
                case MESSAGE_GETCONNECTEDDEVICE:
                    return "MESSAGE_GETCONNECTEDDEVICE";
                case MESSAGE_GETCONNECTINGDEVICE:
                    return "MESSAGE_GETCONNECTINGDEVICE";
                case MESSAGE_VOICECALLPREPROCESS:
                    return "MESSAGE_VOICECALLPREPROCESS";
                case MESSAGE_VOICECALLPOSTPROCESS:
                    return "MESSAGE_VOICECALLPOSTPROCESS";
                case MESSAGE_STARTRING:
                    return "MESSAGE_STARTRING";
                case MESSAGE_STOPRING:
                    return "MESSAGE_STOPRING";
                case 32784:
                    return "MESSAGE_GETSTREAMTYPE";
                case 32785:
                    return "MESSAGE_AUTO_DEVICELIST_UPDATE";
                case 32786:
                    return "MESSAGE_AUTO_DEVICELIST_PLUGIN_UPDATE";
                case 32787:
                    return "MESSAGE_AUTO_DEVICELIST_PLUGOUT_UPDATE";
                case 32788:
                    return "MESSAGE_VOICECALL_AUIDOPARAM_CHANGED";
                case MESSAGE_CONNECT_HIGHEST_PRIORITY_DEVICE:
                    return "MESSAGE_CONNECT_HIGHEST_PRIORITY_DEVICE";
                case MESSAGE_REQUEST_RELEASE_AUDIO_FOCUS:
                    return "MESSAGE_REQUEST_RELEASE_AUDIO_FOCUS";
                case MESSAGE_RECOVER_AUDIO_FOCUS:
                    return "MESSAGE_RECOVER_AUDIO_FOCUS";
                case MESSAGE_FORCE_CONNECTDEVICE:
                    return "MESSAGE_FORCE_CONNECTDEVICE";
                default:
                    return "MESSAGE_NONE";
            }
        }

        @Override
        public void run() {
            AudioDeviceInterface.LogTraceEntry("");
            Looper.prepare();
            this.mMsgHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    HashMap<String, Object> params = null;
                    try {
                        params = (HashMap) msg.obj;
                    } catch (Exception e) {
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.append("TraeAudioManagerLooper msg:");
                    sb.append(msg.what);
                    sb.append(":");
                    sb.append(TraeAudioManagerLooper.this.msgToText(msg.what));
                    sb.append(" _enabled:");
                    sb.append(TraeAudioManagerLooper.this._enabled ? "Y" : "N");
                    QLog.w(TraeAudioManager.TAG, sb.toString());
                    if (msg.what == 32772) {
                        TraeAudioManagerLooper.this.startService(params);
                        return;
                    }
                    if (!TraeAudioManagerLooper.this._enabled) {
                        QLog.w(TraeAudioManager.TAG, "******* disabled ,skip msg******");
                        Intent intent = new Intent();
                        TraeAudioManager.this.sendResBroadcast(intent, params, 1);
                        return;
                    }
                    switch (msg.what) {
                        case TraeAudioManagerLooper.MESSAGE_DISABLE:
                            TraeAudioManagerLooper.this.stopService();
                            break;
                        case 32774:
                            TraeAudioManagerLooper.this.InternalSessionGetDeviceList(params);
                            break;
                        case 32775:
                            TraeAudioManager.this.InternalSessionConnectDevice(params, false);
                            break;
                        case 32776:
                            TraeAudioManager.this.InternalSessionEarAction(params);
                            break;
                        case 32777:
                            TraeAudioManager.this.InternalSessionIsDeviceChangabled(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_GETCONNECTEDDEVICE:
                            TraeAudioManager.this.InternalSessionGetConnectedDevice(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_GETCONNECTINGDEVICE:
                            TraeAudioManager.this.InternalSessionGetConnectingDevice(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_VOICECALLPREPROCESS:
                            TraeAudioManagerLooper.this.InternalVoicecallPreprocess(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_VOICECALLPOSTPROCESS:
                            TraeAudioManagerLooper.this.InternalVoicecallPostprocess(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_STARTRING:
                            TraeAudioManagerLooper.this.InternalStartRing(params);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_STOPRING:
                            TraeAudioManagerLooper.this.InternalStopRing(params);
                            break;
                        case 32784:
                            TraeAudioManagerLooper.this.InternalGetStreamType(params);
                            break;
                        case 32785:
                        case TraeAudioManagerLooper.MESSAGE_CONNECT_HIGHEST_PRIORITY_DEVICE:
                            String highestDev = TraeAudioManager.this._deviceConfigManager.getAvailabledHighestPriorityDevice();
                            String connectedDev = TraeAudioManager.this._deviceConfigManager.getConnectedDevice();
                            QLog.w(TraeAudioManager.TAG, "MESSAGE_AUTO_DEVICELIST_UPDATE  connectedDev:" + connectedDev + " highestDev" + highestDev);
                            if (TraeAudioManager.IsUpdateSceneFlag && TraeAudioManagerLooper.this.IsFirstConnectDeviceFlag) {
                                TraeAudioManagerLooper.this.IsFirstConnectDeviceFlag = false;
                                if (TraeAudioManager.IsMusicScene && !TraeAudioManager.this.IsBluetoothA2dpExisted) {
                                    TraeAudioManager.this.InternalConnectDevice(TraeAudioManager.this._deviceConfigManager.getAvailabledHighestPriorityDevice(TraeAudioManager.DEVICE_BLUETOOTHHEADSET), null, true);
                                    break;
                                } else {
                                    TraeAudioManager.this.InternalConnectDevice(highestDev, null, true);
                                    break;
                                }
                            } else if (!highestDev.equals(connectedDev)) {
                                TraeAudioManager.this.InternalConnectDevice(highestDev, null, false);
                                break;
                            } else {
                                TraeAudioManager.this.InternalNotifyDeviceListUpdate();
                                break;
                            }
                        case 32786:
                            String plugDev = (String) params.get(TraeAudioManager.PARAM_DEVICE);
                            if (TraeAudioManager.this.InternalConnectDevice(plugDev, null, false) != 0) {
                                QLog.w(TraeAudioManager.TAG, " plugin dev:" + plugDev + " sessionConnectedDev:" + TraeAudioManager.this.sessionConnectedDev + " connected fail,auto switch!");
                                TraeAudioManager.this.InternalConnectDevice(TraeAudioManager.this._deviceConfigManager.getAvailabledHighestPriorityDevice(), null, false);
                                break;
                            }
                            break;
                        case 32787:
                            if (TraeAudioManager.this.InternalConnectDevice(TraeAudioManager.this.sessionConnectedDev, null, false) != 0) {
                                QLog.w(TraeAudioManager.TAG, " plugout dev:" + ((String) params.get(TraeAudioManager.PARAM_DEVICE)) + " sessionConnectedDev:" + TraeAudioManager.this.sessionConnectedDev + " connected fail,auto switch!");
                                TraeAudioManager.this.InternalConnectDevice(TraeAudioManager.this._deviceConfigManager.getAvailabledHighestPriorityDevice(), null, false);
                                break;
                            }
                            break;
                        case 32788:
                            Integer st = (Integer) params.get(TraeAudioManager.PARAM_STREAMTYPE);
                            if (st == null) {
                                QLog.e(TraeAudioManager.TAG, " MESSAGE_VOICECALL_AUIDOPARAM_CHANGED params.get(PARAM_STREAMTYPE)==null!!");
                                break;
                            } else {
                                TraeAudioManager.this._streamType = st.intValue();
                                TraeAudioManagerLooper.this.InternalNotifyStreamTypeUpdate(st.intValue());
                                break;
                            }
                        case TraeAudioManagerLooper.MESSAGE_REQUEST_RELEASE_AUDIO_FOCUS:
                            TraeAudioManagerLooper.this.abandonAudioFocus();
                            break;
                        case TraeAudioManagerLooper.MESSAGE_RECOVER_AUDIO_FOCUS:
                            TraeAudioManagerLooper traeAudioManagerLooper = TraeAudioManagerLooper.this;
                            traeAudioManagerLooper.requestAudioFocus(TraeAudioManager.this._streamType);
                            break;
                        case TraeAudioManagerLooper.MESSAGE_FORCE_CONNECTDEVICE:
                            TraeAudioManager.this.InternalConnectDevice(TraeAudioManager.this._deviceConfigManager.getAvailabledHighestPriorityDevice(), null, true);
                            break;
                    }
                }
            };
            _init();
            synchronized (this._started) {
                this._started[0] = true;
                this._started.notifyAll();
            }
            Looper.loop();
            _uninit();
            synchronized (this._started) {
                this._started[0] = false;
                this._started.notifyAll();
            }
            AudioDeviceInterface.LogTraceExit();
        }

        void _init() {
            AudioDeviceInterface.LogTraceEntry("");
            try {
                TraeAudioManager.this._audioSessionHost = new TraeAudioSessionHost();
                TraeAudioManager.this._deviceConfigManager = TraeAudioManager.this.new DeviceConfigManager();
                TraeAudioManager._gHostProcessId = Process.myPid();
                TraeAudioManager.this._am = (AudioManager) TraeAudioManager.this._context.getSystemService("audio");
                TraeAudioManager.this._bluetoothCheck = TraeAudioManager.this.CreateBluetoothCheck(TraeAudioManager.this._context, TraeAudioManager.this._deviceConfigManager);
                IntentFilter filter = new IntentFilter();
                filter.addAction("android.intent.action.HEADSET_PLUG");
                filter.addAction("android.media.AUDIO_BECOMING_NOISY");
                TraeAudioManager.this._bluetoothCheck.addAction(filter);
                filter.addAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_REQUEST);
                TraeAudioManager.this._context.registerReceiver(this._parent, filter);
            } catch (Exception e) {
                QLog.w(TraeAudioManager.TAG, "======7");
            }
            AudioDeviceInterface.LogTraceExit();
        }

        void _prev_startService() {
            try {
                TraeAudioManager.this._am = (AudioManager) TraeAudioManager.this._context.getSystemService("audio");
                if (TraeAudioManager.this._bluetoothCheck == null) {
                    TraeAudioManager.this._bluetoothCheck = TraeAudioManager.this.CreateBluetoothCheck(TraeAudioManager.this._context, TraeAudioManager.this._deviceConfigManager);
                }
                TraeAudioManager.this._context.unregisterReceiver(this._parent);
                IntentFilter filter = new IntentFilter();
                filter.addAction("android.intent.action.HEADSET_PLUG");
                filter.addAction("android.media.AUDIO_BECOMING_NOISY");
                TraeAudioManager.this._bluetoothCheck.addAction(filter);
                filter.addAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_REQUEST);
                TraeAudioManager.this._context.registerReceiver(this._parent, filter);
            } catch (Exception e) {
            }
        }

        void _post_stopService() {
            try {
                if (TraeAudioManager.this._bluetoothCheck != null) {
                    TraeAudioManager.this._bluetoothCheck.release();
                }
                TraeAudioManager.this._bluetoothCheck = null;
                if (TraeAudioManager.this._context != null) {
                    TraeAudioManager.this._context.unregisterReceiver(this._parent);
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_REQUEST);
                    TraeAudioManager.this._context.registerReceiver(this._parent, filter);
                }
            } catch (Exception e) {
            }
        }

        void _uninit() {
            AudioDeviceInterface.LogTraceEntry("");
            try {
                stopService();
                if (TraeAudioManager.this._bluetoothCheck != null) {
                    TraeAudioManager.this._bluetoothCheck.release();
                }
                TraeAudioManager.this._bluetoothCheck = null;
                if (TraeAudioManager.this._context != null) {
                    TraeAudioManager.this._context.unregisterReceiver(this._parent);
                    TraeAudioManager.this._context = null;
                }
                if (TraeAudioManager.this._deviceConfigManager != null) {
                    TraeAudioManager.this._deviceConfigManager.clearConfig();
                }
                TraeAudioManager.this._deviceConfigManager = null;
            } catch (Exception e) {
            }
            AudioDeviceInterface.LogTraceExit();
        }

        int InternalSessionGetDeviceList(HashMap<String, Object> params) {
            Intent intent = new Intent();
            HashMap<String, Object> resParams = TraeAudioManager.this._deviceConfigManager.getSnapParams();
            ArrayList<String> list = (ArrayList) resParams.get(TraeAudioManager.EXTRA_DATA_AVAILABLEDEVICE_LIST);
            String con = (String) resParams.get(TraeAudioManager.EXTRA_DATA_CONNECTEDDEVICE);
            String prevCon = (String) resParams.get(TraeAudioManager.EXTRA_DATA_PREV_CONNECTEDDEVICE);
            intent.putExtra(TraeAudioManager.EXTRA_DATA_AVAILABLEDEVICE_LIST, (String[]) list.toArray(new String[0]));
            intent.putExtra(TraeAudioManager.EXTRA_DATA_CONNECTEDDEVICE, con);
            intent.putExtra(TraeAudioManager.EXTRA_DATA_PREV_CONNECTEDDEVICE, prevCon);
            intent.putExtra(TraeAudioManager.EXTRA_DATA_IF_HAS_BLUETOOTH_THIS_IS_NAME, TraeAudioManager.this._deviceConfigManager.getBluetoothName());
            TraeAudioManager.this.sendResBroadcast(intent, params, 0);
            return 0;
        }

        void requestAudioFocus(int streamType) {
            if (ClientInfo.VERSION_SDK_INT > 8 && this.mAudioFocusChangeListener == null) {
                this.mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
                    @Override
                    public void onAudioFocusChange(int focusChange) {
                        QLog.w(TraeAudioManager.TAG, "focusChange:" + focusChange + " _focusSteamType:" + TraeAudioManagerLooper.this._focusSteamType + " currMode:" + TraeAudioManager.this._am.getMode() + " _activeMode:" + TraeAudioManager.this._activeMode);
                        if (focusChange != -1 && focusChange != -2 && focusChange == -3) {
                        }
                    }
                };
                if (TraeAudioManager.this._am != null) {
                    try {
                        int ret = TraeAudioManager.this._am.requestAudioFocus(this.mAudioFocusChangeListener, streamType, 1);
                        if (ret != 1) {
                            QLog.e(TraeAudioManager.TAG, "request audio focus fail. " + ret + " mode:" + TraeAudioManager.this._am.getMode());
                        }
                        this._focusSteamType = streamType;
                        QLog.w(TraeAudioManager.TAG, "-------requestAudioFocus _focusSteamType:" + this._focusSteamType);
                    } catch (SecurityException ignored) {
                        QLog.e(TraeAudioManager.TAG, "request audio focus exception. " + ignored);
                    }
                }
            }
        }

        void abandonAudioFocus() {
            if (ClientInfo.VERSION_SDK_INT > 8 && TraeAudioManager.this._am != null && this.mAudioFocusChangeListener != null) {
                QLog.w(TraeAudioManager.TAG, "-------abandonAudioFocus _focusSteamType:" + this._focusSteamType);
                TraeAudioManager.this._am.abandonAudioFocus(this.mAudioFocusChangeListener);
                this.mAudioFocusChangeListener = null;
            }
        }

        int InternalVoicecallPreprocess(HashMap<String, Object> params) {
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode);
            if (params == null) {
                return -1;
            }
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " InternalVoicecallPreprocess am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode == 1) {
                Intent intent = new Intent();
                TraeAudioManager.this.sendResBroadcast(intent, params, 2);
                return -1;
            }
            this._voiceCallSessionID = ((Long) params.get(TraeAudioManager.PARAM_SESSIONID)).longValue();
            this._voiceCallOperation = (String) params.get(TraeAudioManager.PARAM_OPERATION);
            TraeAudioManager.this._activeMode = 1;
            TraeAudioManager traeAudioManager = TraeAudioManager.this;
            traeAudioManager._prevMode = traeAudioManager._am.getMode();
            Integer.valueOf(-1);
            Integer.valueOf(0);
            Integer mode = (Integer) params.get(TraeAudioManager.PARAM_MODEPOLICY);
            if (mode == null) {
                QLog.e(TraeAudioManager.TAG, " params.get(PARAM_MODEPOLICY)==null!!");
                TraeAudioManager.this._modePolicy = -1;
            } else {
                TraeAudioManager.this._modePolicy = mode.intValue();
            }
            QLog.e(TraeAudioManager.TAG, "  _modePolicy:" + TraeAudioManager.this._modePolicy);
            Integer streamType = (Integer) params.get(TraeAudioManager.PARAM_STREAMTYPE);
            if (streamType == null) {
                QLog.e(TraeAudioManager.TAG, " params.get(PARAM_STREAMTYPE)==null!!");
                TraeAudioManager.this._streamType = 0;
            } else {
                TraeAudioManager.this._streamType = streamType.intValue();
            }
            if ((TraeAudioManager.nSceneMode == 6 || TraeAudioManager.nSceneMode == 8) && TraeAudioManager.nSpecialModeBypass3A == 1 && TraeAudioManager.nSpeakerStreamType == 1) {
                QLog.w(TraeAudioManager.TAG, "VOIP select different mode,bypass 3A");
                if (TraeAudioManager.this._deviceConfigManager.getConnectedDevice().equals(TraeAudioManager.DEVICE_WIREDHEADSET)) {
                    TraeAudioManager.this.InternalSetMode(0);
                } else if (TraeAudioManager.isCloseSystemAPM(TraeAudioManager.this._modePolicy) && TraeAudioManager.this._activeMode != 2 && TraeAudioManager.this._deviceConfigManager != null) {
                    if (TraeAudioManager.this._deviceConfigManager.getConnectedDevice().equals(TraeAudioManager.DEVICE_SPEAKERPHONE)) {
                        TraeAudioManager.this.InternalSetMode(0);
                    } else {
                        TraeAudioManager.this.InternalSetMode(3);
                    }
                } else {
                    TraeAudioManager traeAudioManager2 = TraeAudioManager.this;
                    traeAudioManager2.InternalSetMode(TraeAudioManager.getCallAudioMode(traeAudioManager2._modePolicy));
                }
            } else if (TraeAudioManager.isCloseSystemAPM(TraeAudioManager.this._modePolicy) && TraeAudioManager.this._activeMode != 2 && TraeAudioManager.this._deviceConfigManager != null) {
                if (TraeAudioManager.this._deviceConfigManager.getConnectedDevice().equals(TraeAudioManager.DEVICE_SPEAKERPHONE)) {
                    TraeAudioManager.this.InternalSetMode(0);
                } else {
                    TraeAudioManager.this.InternalSetMode(3);
                }
            } else {
                TraeAudioManager traeAudioManager3 = TraeAudioManager.this;
                traeAudioManager3.InternalSetMode(TraeAudioManager.getCallAudioMode(traeAudioManager3._modePolicy));
            }
            Intent intent2 = new Intent();
            TraeAudioManager.this.sendResBroadcast(intent2, params, 0);
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        int InternalVoicecallPostprocess(HashMap<String, Object> params) {
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode);
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " InternalVoicecallPostprocess am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode != 1) {
                QLog.e(TraeAudioManager.TAG, " not ACTIVE_VOICECALL!!");
                Intent intent = new Intent();
                TraeAudioManager.this.sendResBroadcast(intent, params, 3);
                return -1;
            }
            TraeAudioManager.this._activeMode = 0;
            if (TraeAudioManager.this._switchThread != null) {
                QLog.w(TraeAudioManager.TAG, "_switchThread:" + TraeAudioManager.this._switchThread.getDeviceName());
                TraeAudioManager.this._switchThread.quit();
                TraeAudioManager.this._switchThread = null;
            }
            abandonAudioFocus();
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        int interruptVoicecallPostprocess() {
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode);
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode != 1) {
                QLog.e(TraeAudioManager.TAG, " not ACTIVE_RING!!");
                return -1;
            }
            TraeAudioManager.this._activeMode = 0;
            if (TraeAudioManager.this._prevMode != -1) {
                TraeAudioManager traeAudioManager = TraeAudioManager.this;
                traeAudioManager.InternalSetMode(traeAudioManager._prevMode);
            }
            HashMap<String, Object> params = new HashMap<>();
            params.put(TraeAudioManager.PARAM_SESSIONID, Long.valueOf(this._voiceCallSessionID));
            params.put(TraeAudioManager.PARAM_OPERATION, this._voiceCallOperation);
            Intent intent = new Intent();
            TraeAudioManager.this.sendResBroadcast(intent, params, 6);
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        int InternalStartRing(HashMap<String, Object> params) {
            int dataSource;
            int rsId;
            Uri res;
            String strFilePath;
            boolean bLoop;
            int loopCount;
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode);
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " InternalStartRing am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode == 2) {
                interruptRing();
            }
            try {
                this._ringSessionID = ((Long) params.get(TraeAudioManager.PARAM_SESSIONID)).longValue();
                this._ringOperation = (String) params.get(TraeAudioManager.PARAM_OPERATION);
                this._ringUserdata = (String) params.get(TraeAudioManager.PARAM_RING_USERDATA_STRING);
                dataSource = ((Integer) params.get(TraeAudioManager.PARAM_RING_DATASOURCE)).intValue();
                QLog.w(TraeAudioManager.TAG, "  dataSource:" + dataSource);
                rsId = ((Integer) params.get(TraeAudioManager.PARAM_RING_RSID)).intValue();
                try {
                    res = (Uri) params.get(TraeAudioManager.PARAM_RING_URI);
                    try {
                        strFilePath = (String) params.get(TraeAudioManager.PARAM_RING_FILEPATH);
                        try {
                            bLoop = ((Boolean) params.get(TraeAudioManager.PARAM_RING_LOOP)).booleanValue();
                            try {
                                loopCount = ((Integer) params.get(TraeAudioManager.PARAM_RING_LOOPCOUNT)).intValue();
                            } catch (Exception e) {
                            }
                        } catch (Exception e2) {
                        }
                    } catch (Exception e3) {
                    }
                } catch (Exception e4) {
                }
            } catch (Exception e5) {
            }
            try {
                boolean ringMode = ((Boolean) params.get(TraeAudioManager.PARAM_RING_MODE)).booleanValue();
                if (TraeAudioManager.this._activeMode != 1) {
                    TraeAudioManager.this._activeMode = 2;
                }
                Intent intent = new Intent();
                intent.putExtra(TraeAudioManager.PARAM_RING_USERDATA_STRING, this._ringUserdata);
                TraeAudioManager.this.sendResBroadcast(intent, params, 0);
                this._preRingMode = TraeAudioManager.this._am.getMode();
                this._ringPlayer.playRing(dataSource, rsId, res, strFilePath, bLoop, loopCount, ringMode, TraeAudioManager.this._activeMode == 1, TraeAudioManager.this._streamType);
                QLog.w(TraeAudioManager.TAG, " _ringUserdata:" + this._ringUserdata + " DurationMS:" + this._ringPlayer.getDuration());
                if (!this._ringPlayer.hasCall()) {
                    requestAudioFocus(this._ringPlayer.getStreamType());
                }
                InternalNotifyStreamTypeUpdate(this._ringPlayer.getStreamType());
                AudioDeviceInterface.LogTraceExit();
                return 0;
            } catch (Exception e6) {
                QLog.e(TraeAudioManager.TAG, " startRing err params");
                return -1;
            }
        }

        int InternalStopRing(HashMap<String, Object> params) {
            TraeMediaPlayer traeMediaPlayer;
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode + " _preRingMode:" + this._preRingMode);
            if (TraeAudioManager.this._am == null || (traeMediaPlayer = this._ringPlayer) == null) {
                QLog.e(TraeAudioManager.TAG, " InternalStopRing am==null!!");
                return -1;
            }
            traeMediaPlayer.stopRing();
            if (!this._ringPlayer.hasCall() && TraeAudioManager.this._activeMode == 2) {
                abandonAudioFocus();
                TraeAudioManager.this._activeMode = 0;
            }
            Intent intent = new Intent();
            intent.putExtra(TraeAudioManager.PARAM_RING_USERDATA_STRING, this._ringUserdata);
            TraeAudioManager.this.sendResBroadcast(intent, params, 0);
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        int InternalGetStreamType(HashMap<String, Object> params) {
            int st;
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode + " _preRingMode:" + this._preRingMode);
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " InternalStopRing am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode == 2) {
                st = this._ringPlayer.getStreamType();
            } else {
                st = TraeAudioManager.this._streamType;
            }
            Intent intent = new Intent();
            intent.putExtra(TraeAudioManager.EXTRA_DATA_STREAMTYPE, st);
            TraeAudioManager.this.sendResBroadcast(intent, params, 0);
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        int InternalNotifyStreamTypeUpdate(final int st) {
            if (TraeAudioManager.this._context == null) {
                return -1;
            }
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    intent.setAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_NOTIFY);
                    intent.putExtra(TraeAudioManager.PARAM_OPERATION, TraeAudioManager.NOTIFY_STREAMTYPE_UPDATE);
                    intent.putExtra(TraeAudioManager.EXTRA_DATA_STREAMTYPE, st);
                    if (TraeAudioManager.this._context != null) {
                        TraeAudioManager.this._context.sendBroadcast(intent);
                    }
                }
            });
            return 0;
        }

        int interruptRing() {
            AudioDeviceInterface.LogTraceEntry(" activeMode:" + TraeAudioManager.this._activeMode + " _preRingMode:" + this._preRingMode);
            if (TraeAudioManager.this._am == null) {
                QLog.e(TraeAudioManager.TAG, " interruptRing am==null!!");
                return -1;
            }
            if (TraeAudioManager.this._activeMode != 2) {
                QLog.e(TraeAudioManager.TAG, " not ACTIVE_RING!!");
                return -1;
            }
            this._ringPlayer.stopRing();
            abandonAudioFocus();
            TraeAudioManager.this._activeMode = 0;
            HashMap<String, Object> params = new HashMap<>();
            params.put(TraeAudioManager.PARAM_SESSIONID, Long.valueOf(this._ringSessionID));
            params.put(TraeAudioManager.PARAM_OPERATION, this._ringOperation);
            Intent intent = new Intent();
            intent.putExtra(TraeAudioManager.PARAM_RING_USERDATA_STRING, this._ringUserdata);
            TraeAudioManager.this.sendResBroadcast(intent, params, 4);
            AudioDeviceInterface.LogTraceExit();
            return 0;
        }

        void notifyRingCompletion() {
            HashMap<String, Object> params = new HashMap<>();
            params.put(TraeAudioManager.PARAM_SESSIONID, Long.valueOf(this._ringSessionID));
            params.put(TraeAudioManager.PARAM_OPERATION, TraeAudioManager.NOTIFY_RING_COMPLETION);
            Intent intent = new Intent();
            intent.putExtra(TraeAudioManager.PARAM_RING_USERDATA_STRING, this._ringUserdata);
            TraeAudioManager.this.sendResBroadcast(intent, params, 0);
        }
    }

    public static int OpenSpeaker(boolean speakerOn) {
        int iRet = -1;
        _glock.lock();
        TraeAudioManager traeAudioManager = _ginstance;
        if (traeAudioManager != null) {
            iRet = 0;
            if (speakerOn != traeAudioManager._speakerOn) {
                traeAudioManager._speakerOn = speakerOn;
                iRet = traeAudioManager.InternalSetSpeaker(traeAudioManager._context, speakerOn);
            }
        } else {
            QLog.w(TAG, "TraeAudioManager|static SetSpeakerForTest|null == _ginstance");
        }
        _glock.unlock();
        return iRet;
    }

    public static int SetSpeakerForTest(Context context, boolean speakerOn) {
        int iRet = -1;
        _glock.lock();
        TraeAudioManager traeAudioManager = _ginstance;
        if (traeAudioManager != null) {
            iRet = traeAudioManager.InternalSetSpeaker(context, speakerOn);
        } else {
            QLog.w(TAG, "TraeAudioManager|static SetSpeakerForTest|null == _ginstance");
        }
        _glock.unlock();
        return iRet;
    }

    int InternalSetSpeaker(Context context, boolean speakerOn) {
        QLog.i(TAG, "InternalSetSpeaker entry. speakerOn:" + speakerOn);
        if (context == null) {
            QLog.e(TAG, "Could not InternalSetSpeaker - no context");
            return -1;
        }
        AudioManager am = (AudioManager) context.getSystemService("audio");
        if (am == null) {
            QLog.e(TAG, "Could not InternalSetSpeaker - no audio manager");
            return -1;
        }
        boolean old = am.isSpeakerphoneOn();
        if (old != speakerOn) {
            am.setSpeakerphoneOn(speakerOn);
        }
        int res = am.isSpeakerphoneOn() == speakerOn ? 0 : -1;
        QLog.i(TAG, String.format("InternalSetSpeaker exit:Speaker:%s->%s, mode=%s", Boolean.valueOf(old), Boolean.valueOf(am.isSpeakerphoneOn()), Integer.valueOf(am.getMode())));
        return res;
    }

    void InternalSetMode(int audioMode) {
        QLog.w(TAG, "SetMode entry:" + audioMode);
        AudioManager audioManager = this._am;
        if (audioManager == null) {
            QLog.w(TAG, "setMode:" + audioMode + " fail am=null");
            return;
        }
        try {
            audioManager.setMode(audioMode);
        } catch (Exception e) {
            QLog.e(TAG, "setMode:" + audioMode + " exception");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("setMode:");
        sb.append(audioMode);
        sb.append(this._am.getMode() != audioMode ? "fail" : "success");
        QLog.w(TAG, sb.toString());
    }

    public static int registerAudioSession(TraeAudioSession _traeAs, boolean bRegister, long nSessionId, Context ctx) {
        TraeAudioSessionHost traeAudioSessionHost;
        int iRet = -1;
        _glock.lock();
        TraeAudioManager traeAudioManager = _ginstance;
        if (traeAudioManager != null && (traeAudioSessionHost = traeAudioManager._audioSessionHost) != null) {
            if (bRegister) {
                traeAudioSessionHost.add(_traeAs, nSessionId, ctx);
            } else {
                traeAudioSessionHost.remove(nSessionId);
            }
            iRet = 0;
        }
        _glock.unlock();
        return iRet;
    }

    public static int sendMessage(int nMsg, HashMap<String, Object> params) {
        int iRet = -1;
        _glock.lock();
        TraeAudioManager traeAudioManager = _ginstance;
        if (traeAudioManager != null) {
            iRet = traeAudioManager.internalSendMessage(nMsg, params);
        }
        _glock.unlock();
        return iRet;
    }

    public static int init(Context ctx) {
        _glock.lock();
        if (_ginstance == null) {
            Log.w(TAG, "TraeAudioManager first init _ginstance:" + _ginstance);
        }
        if (_ginstance == null) {
            _ginstance = new TraeAudioManager(ctx);
        }
        _glock.unlock();
        return 0;
    }

    public static void uninit() {
        _glock.lock();
        Log.w(TAG, "TraeAudioManager uninit _ginstance:" + _ginstance);
        TraeAudioManager traeAudioManager = _ginstance;
        if (traeAudioManager != null) {
            traeAudioManager.release();
            _ginstance = null;
        }
        _glock.unlock();
    }

    TraeAudioManager(Context ctx) {
        this._context = null;
        this.mTraeAudioManagerLooper = null;
        AudioDeviceInterface.LogTraceEntry(" context:" + ctx);
        if (ctx == null) {
            return;
        }
        this._context = ctx;
        this.mTraeAudioManagerLooper = new TraeAudioManagerLooper(this);
        AudioDeviceInterface.LogTraceExit();
    }

    public void release() {
        AudioDeviceInterface.LogTraceEntry("");
        TraeAudioManagerLooper traeAudioManagerLooper = this.mTraeAudioManagerLooper;
        if (traeAudioManagerLooper != null) {
            traeAudioManagerLooper.quit();
            this.mTraeAudioManagerLooper = null;
        }
        AudioDeviceInterface.LogTraceExit();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || context == null) {
            QLog.d(TAG, "onReceive intent or context is null!");
            return;
        }
        try {
            String strAction = intent.getAction();
            String strOption = intent.getStringExtra(PARAM_OPERATION);
            QLog.w(TAG, "TraeAudioManager|onReceive::Action:" + intent.getAction());
            if (this._deviceConfigManager == null) {
                QLog.d(TAG, "_deviceConfigManager null!");
                return;
            }
            boolean prevWiredHeadset = this._deviceConfigManager.getVisible(DEVICE_WIREDHEADSET);
            boolean prevBluetoothHeadset = this._deviceConfigManager.getVisible(DEVICE_BLUETOOTHHEADSET);
            if ("android.intent.action.HEADSET_PLUG".equals(intent.getAction())) {
                onHeadsetPlug(context, intent);
                if (!prevWiredHeadset && this._deviceConfigManager.getVisible(DEVICE_WIREDHEADSET)) {
                    checkDevicePlug(DEVICE_WIREDHEADSET, true);
                }
                if (prevWiredHeadset && !this._deviceConfigManager.getVisible(DEVICE_WIREDHEADSET)) {
                    checkDevicePlug(DEVICE_WIREDHEADSET, false);
                    return;
                }
                return;
            }
            if (!"android.media.AUDIO_BECOMING_NOISY".equals(intent.getAction())) {
                if (ACTION_TRAEAUDIOMANAGER_REQUEST.equals(strAction)) {
                    QLog.w(TAG, "   OPERATION:" + strOption);
                    if (OPERATION_STARTSERVICE.equals(strOption)) {
                        startService(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, intent.getStringExtra(EXTRA_DATA_DEVICECONFIG));
                        return;
                    }
                    if (OPERATION_STOPSERVICE.equals(strOption)) {
                        stopService(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_GETDEVICELIST.equals(strOption)) {
                        getDeviceList(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_GETSTREAMTYPE.equals(strOption)) {
                        getStreamType(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_CONNECTDEVICE.equals(strOption)) {
                        connectDevice(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, intent.getStringExtra(CONNECTDEVICE_DEVICENAME));
                        return;
                    }
                    if (OPERATION_FORCE_CONNECTDEVICE.equals(strOption)) {
                        forceConnectDevice(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, intent.getStringExtra(CONNECTDEVICE_DEVICENAME));
                        return;
                    }
                    if (OPERATION_CONNECT_HIGHEST_PRIORITY_DEVICE.equals(strOption)) {
                        connectHighestPriorityDevice(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_EARACTION.equals(strOption)) {
                        earAction(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, intent.getIntExtra(EXTRA_EARACTION, -1));
                        return;
                    }
                    if (OPERATION_ISDEVICECHANGABLED.equals(strOption)) {
                        isDeviceChangabled(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_GETCONNECTEDDEVICE.equals(strOption)) {
                        getConnectedDevice(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_GETCONNECTINGDEVICE.equals(strOption)) {
                        getConnectingDevice(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_VOICECALL_PREPROCESS.equals(strOption)) {
                        int modePolicy = intent.getIntExtra(PARAM_MODEPOLICY, -1);
                        int streamType = intent.getIntExtra(PARAM_STREAMTYPE, -1);
                        voicecallPreprocess(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, modePolicy, streamType);
                        return;
                    }
                    if (OPERATION_VOICECALL_POSTPROCESS.equals(strOption)) {
                        voicecallPostprocess(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                        return;
                    }
                    if (OPERATION_VOICECALL_AUDIOPARAM_CHANGED.equals(strOption)) {
                        int modePolicy2 = intent.getIntExtra(PARAM_MODEPOLICY, -1);
                        int streamType2 = intent.getIntExtra(PARAM_STREAMTYPE, -1);
                        voiceCallAudioParamChanged(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, modePolicy2, streamType2);
                        return;
                    } else {
                        if (!OPERATION_STARTRING.equals(strOption)) {
                            if (OPERATION_STOPRING.equals(strOption)) {
                                stopRing(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false);
                                return;
                            }
                            return;
                        }
                        int dataSource = intent.getIntExtra(PARAM_RING_DATASOURCE, -1);
                        int rsId = intent.getIntExtra(PARAM_RING_RSID, -1);
                        Uri res = (Uri) intent.getParcelableExtra(PARAM_RING_URI);
                        String strFilePath = intent.getStringExtra(PARAM_RING_FILEPATH);
                        boolean bLoop = intent.getBooleanExtra(PARAM_RING_LOOP, false);
                        String userData = intent.getStringExtra(PARAM_RING_USERDATA_STRING);
                        int loopCount = intent.getIntExtra(PARAM_RING_LOOPCOUNT, 1);
                        boolean ringMode = intent.getBooleanExtra(PARAM_RING_MODE, false);
                        startRing(strOption, intent.getLongExtra(PARAM_SESSIONID, Long.MIN_VALUE), false, dataSource, rsId, res, strFilePath, bLoop, loopCount, userData, ringMode);
                        return;
                    }
                }
                if (this._deviceConfigManager != null) {
                    if (this._bluetoothCheck != null) {
                        this._bluetoothCheck.onReceive(context, intent, this._deviceConfigManager);
                    }
                    if (!prevBluetoothHeadset && this._deviceConfigManager.getVisible(DEVICE_BLUETOOTHHEADSET)) {
                        checkDevicePlug(DEVICE_BLUETOOTHHEADSET, true);
                    }
                    if (prevBluetoothHeadset && !this._deviceConfigManager.getVisible(DEVICE_BLUETOOTHHEADSET)) {
                        checkDevicePlug(DEVICE_BLUETOOTHHEADSET, false);
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    void onHeadsetPlug(Context context, Intent intent) {
        String name = intent.getStringExtra(MediationMetaData.KEY_NAME);
        if (name == null) {
            name = "unkonw";
        }
        String logs = " [" + name + "] ";
        int state = intent.getIntExtra(AdOperationMetric.INIT_STATE, -1);
        if (state != -1) {
            StringBuilder sb = new StringBuilder();
            sb.append(logs);
            sb.append(state == 0 ? "unplugged" : "plugged");
            logs = sb.toString();
        }
        String logs2 = logs + " mic:";
        int microphone = intent.getIntExtra("microphone", -1);
        if (microphone != -1) {
            StringBuilder sb2 = new StringBuilder();
            sb2.append(logs2);
            sb2.append(microphone == 1 ? "Y" : "unkown");
            logs2 = sb2.toString();
        }
        QLog.w(TAG, "onHeadsetPlug:: " + logs2);
        this._deviceConfigManager.setVisible(DEVICE_WIREDHEADSET, 1 == state);
        QLog.w(TAG, "onHeadsetPlug exit");
    }

    int internalSendMessage(int nMsg, HashMap<String, Object> params) {
        TraeAudioManagerLooper traeAudioManagerLooper = this.mTraeAudioManagerLooper;
        if (traeAudioManagerLooper == null) {
            return -1;
        }
        int iRet = traeAudioManagerLooper.sendMessage(nMsg, params);
        return iRet;
    }

    static int getDeviceList(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(32774, params);
    }

    static int getStreamType(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(32784, params);
    }

    static int startService(String strOption, long nSessionId, boolean bHostside, String deviceConfig) {
        if (deviceConfig.length() <= 0) {
            return -1;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(EXTRA_DATA_DEVICECONFIG, deviceConfig);
        return sendMessage(32772, params);
    }

    static int stopService(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_DISABLE, params);
    }

    static int connectDevice(String strOption, long nSessionId, boolean bHostside, String strDevice) {
        if (strDevice == null) {
            return -1;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(CONNECTDEVICE_DEVICENAME, strDevice);
        params.put(PARAM_DEVICE, strDevice);
        return sendMessage(32775, params);
    }

    static int forceConnectDevice(String strOption, long nSessionId, boolean bHostside, String strDevice) {
        if (strDevice == null) {
            return -1;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(CONNECTDEVICE_DEVICENAME, strDevice);
        params.put(PARAM_DEVICE, strDevice);
        return sendMessage(TraeAudioManagerLooper.MESSAGE_FORCE_CONNECTDEVICE, params);
    }

    static int connectHighestPriorityDevice(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_CONNECT_HIGHEST_PRIORITY_DEVICE, params);
    }

    static int earAction(String strOption, long nSessionId, boolean bHostside, int earAction) {
        if (earAction != 0 && earAction != 1) {
            return -1;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(EXTRA_EARACTION, Integer.valueOf(earAction));
        return sendMessage(32776, params);
    }

    static int isDeviceChangabled(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(32777, params);
    }

    static int getConnectedDevice(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_GETCONNECTEDDEVICE, params);
    }

    static int getConnectingDevice(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_GETCONNECTINGDEVICE, params);
    }

    static int voicecallPreprocess(String strOption, long nSessionId, boolean bHostside, int modePolicy, int streamType) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(PARAM_MODEPOLICY, Integer.valueOf(modePolicy));
        params.put(PARAM_STREAMTYPE, Integer.valueOf(streamType));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_VOICECALLPREPROCESS, params);
    }

    static int voicecallPostprocess(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_VOICECALLPOSTPROCESS, params);
    }

    static int voiceCallAudioParamChanged(String strOption, long nSessionId, boolean bHostside, int modePolicy, int streamType) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(PARAM_MODEPOLICY, Integer.valueOf(modePolicy));
        params.put(PARAM_STREAMTYPE, Integer.valueOf(streamType));
        return sendMessage(32788, params);
    }

    static int startRing(String strOption, long nSessionId, boolean bHostside, int dataSource, int rsId, Uri res, String strFilePath, boolean bLoop, int loopCount, String userData, boolean ringMode) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        params.put(PARAM_RING_DATASOURCE, Integer.valueOf(dataSource));
        params.put(PARAM_RING_RSID, Integer.valueOf(rsId));
        params.put(PARAM_RING_URI, res);
        params.put(PARAM_RING_FILEPATH, strFilePath);
        params.put(PARAM_RING_LOOP, Boolean.valueOf(bLoop));
        params.put(PARAM_RING_LOOPCOUNT, Integer.valueOf(loopCount));
        params.put(PARAM_RING_MODE, Boolean.valueOf(ringMode));
        params.put(PARAM_RING_USERDATA_STRING, userData);
        return sendMessage(TraeAudioManagerLooper.MESSAGE_STARTRING, params);
    }

    static int stopRing(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_STOPRING, params);
    }

    static int requestReleaseAudioFocus(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_REQUEST_RELEASE_AUDIO_FOCUS, params);
    }

    static int recoverAudioFocus(String strOption, long nSessionId, boolean bHostside) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(PARAM_SESSIONID, Long.valueOf(nSessionId));
        params.put(PARAM_OPERATION, strOption);
        params.put(PARAM_ISHOSTSIDE, Boolean.valueOf(bHostside));
        return sendMessage(TraeAudioManagerLooper.MESSAGE_RECOVER_AUDIO_FOCUS, params);
    }

    int InternalSessionConnectDevice(HashMap<String, Object> params, boolean IsForceConnectDevice) {
        AudioDeviceInterface.LogTraceEntry("");
        if (params == null || this._context == null) {
            return -1;
        }
        if (IsMusicScene) {
            QLog.w(TAG, "MusicScene: InternalSessionConnectDevice failed");
            return -1;
        }
        String devName = (String) params.get(PARAM_DEVICE);
        Log.w(TAG, "ConnectDevice: " + devName);
        if (!IsEarPhoneSupported && devName.equals(DEVICE_EARPHONE)) {
            QLog.e(TAG, "InternalSessionConnectDevice IsEarPhoneSupported = false, Connect device:" + devName + " failed");
            return -1;
        }
        int err = 0;
        boolean bChangabled = InternalIsDeviceChangeable();
        if (!checkDevName(devName)) {
            err = 7;
        } else if (!this._deviceConfigManager.getVisible(devName)) {
            err = 8;
        } else if (!bChangabled) {
            err = 9;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("sessonID:");
        sb.append((Long) params.get(PARAM_SESSIONID));
        sb.append(" devName:");
        sb.append(devName);
        sb.append(" bChangabled:");
        sb.append(bChangabled ? "Y" : "N");
        sb.append(" err:");
        sb.append(err);
        QLog.w(TAG, sb.toString());
        if (err != 0) {
            Intent intent = new Intent();
            intent.putExtra(CONNECTDEVICE_RESULT_DEVICENAME, (String) params.get(PARAM_DEVICE));
            sendResBroadcast(intent, params, err);
            return -1;
        }
        if (!IsForceConnectDevice && devName.equals(this._deviceConfigManager.getConnectedDevice())) {
            QLog.e(TAG, " --has connected!");
            Intent intent2 = new Intent();
            intent2.putExtra(CONNECTDEVICE_RESULT_DEVICENAME, (String) params.get(PARAM_DEVICE));
            sendResBroadcast(intent2, params, err);
            return 0;
        }
        QLog.w(TAG, " --connecting...");
        InternalConnectDevice(devName, params, IsForceConnectDevice);
        AudioDeviceInterface.LogTraceExit();
        return 0;
    }

    int InternalSessionEarAction(HashMap<String, Object> params) {
        return 0;
    }

    int InternalConnectDevice(String devName, HashMap<String, Object> needResParams, boolean IsForceConnectDevice) {
        AudioDeviceInterface.LogTraceEntry(" devName:" + devName);
        if (devName == null) {
            return -1;
        }
        if (IsMusicScene && devName.equals(DEVICE_EARPHONE)) {
            QLog.e(TAG, "MusicScene, Connect device:" + devName + " failed");
            return -1;
        }
        if (!IsEarPhoneSupported && devName.equals(DEVICE_EARPHONE)) {
            QLog.e(TAG, "IsEarPhoneSupported = false, Connect device:" + devName + " failed");
            return -1;
        }
        if (!IsForceConnectDevice && !this._deviceConfigManager.getConnectedDevice().equals(DEVICE_NONE) && devName.equals(this._deviceConfigManager.getConnectedDevice())) {
            return 0;
        }
        if (!checkDevName(devName) || !this._deviceConfigManager.getVisible(devName)) {
            QLog.e(TAG, " checkDevName fail");
            return -1;
        }
        if (!InternalIsDeviceChangeable()) {
            QLog.e(TAG, " InternalIsDeviceChangeable fail");
            return -1;
        }
        this._deviceConfigManager.setConnecting(devName);
        if (this._switchThread != null) {
            QLog.w(TAG, "_switchThread:" + this._switchThread.getDeviceName());
            this._switchThread.quit();
            this._switchThread = null;
        }
        if (devName.equals(DEVICE_EARPHONE)) {
            this._switchThread = new earphoneSwitchThread();
        } else if (devName.equals(DEVICE_SPEAKERPHONE)) {
            this._switchThread = new speakerSwitchThread();
        } else if (devName.equals(DEVICE_WIREDHEADSET)) {
            this._switchThread = new headsetSwitchThread();
        } else if (devName.equals(DEVICE_BLUETOOTHHEADSET)) {
            this._switchThread = new bluetoothHeadsetSwitchThread();
        }
        switchThread switchthread = this._switchThread;
        if (switchthread != null) {
            switchthread.setDeviceConnectParam(needResParams);
            this._switchThread.start();
        }
        AudioDeviceInterface.LogTraceExit();
        return 0;
    }

    abstract class switchThread extends Thread {
        boolean _running = true;
        boolean[] _exited = {false};
        HashMap<String, Object> _params = null;
        long _usingtime = 0;

        public abstract void _quit();

        public abstract void _run();

        public abstract String getDeviceName();

        switchThread() {
            QLog.w(TraeAudioManager.TAG, " ++switchThread:" + getDeviceName());
        }

        public void setDeviceConnectParam(HashMap<String, Object> params) {
            this._params = params;
        }

        void updateStatus() {
            TraeAudioManager.this._deviceConfigManager.setConnected(getDeviceName());
            processDeviceConnectRes(0);
        }

        void processDeviceConnectRes(int err) {
            TraeAudioManager.this._deviceConfigManager.setConnected(getDeviceName());
            TraeAudioManager.this.InternalNotifyDeviceChangableUpdate();
            AudioDeviceInterface.LogTraceEntry(getDeviceName() + " err:" + err);
            if (this._params == null) {
                TraeAudioManager.this.InternalNotifyDeviceListUpdate();
                return;
            }
            TraeAudioManager traeAudioManager = TraeAudioManager.this;
            traeAudioManager.sessionConnectedDev = traeAudioManager._deviceConfigManager.getConnectedDevice();
            Long sid = (Long) this._params.get(TraeAudioManager.PARAM_SESSIONID);
            QLog.w(TraeAudioManager.TAG, " sessonID:" + sid);
            if (sid == null || sid.longValue() == Long.MIN_VALUE) {
                TraeAudioManager.this.InternalNotifyDeviceListUpdate();
                QLog.w(TraeAudioManager.TAG, "processDeviceConnectRes sid null,don't send res");
                return;
            }
            Intent intent = new Intent();
            intent.putExtra(TraeAudioManager.CONNECTDEVICE_RESULT_DEVICENAME, (String) this._params.get(TraeAudioManager.PARAM_DEVICE));
            if (TraeAudioManager.this.sendResBroadcast(intent, this._params, err) == 0) {
                TraeAudioManager.this.InternalNotifyDeviceListUpdate();
            }
            AudioDeviceInterface.LogTraceExit();
        }

        @Override
        public void run() {
            AudioDeviceInterface.LogTraceEntry(getDeviceName());
            TraeAudioManager.this.InternalNotifyDeviceChangableUpdate();
            _run();
            synchronized (this._exited) {
                this._exited[0] = true;
                this._exited.notifyAll();
            }
            AudioDeviceInterface.LogTraceExit();
        }

        public void quit() {
            AudioDeviceInterface.LogTraceEntry(getDeviceName());
            this._running = false;
            QLog.w(TraeAudioManager.TAG, " quit:" + getDeviceName() + " _running:" + this._running);
            interrupt();
            synchronized (this._exited) {
                if (!this._exited[0]) {
                    try {
                        this._exited.wait(10000L);
                    } catch (InterruptedException e) {
                    }
                }
                _quit();
            }
            AudioDeviceInterface.LogTraceExit();
        }
    }

    class earphoneSwitchThread extends switchThread {
        earphoneSwitchThread() {
            super();
        }

        @Override
        public void _run() {
            int i = 0;
            if (TraeAudioManager.IsUpdateSceneFlag) {
                TraeAudioManager traeAudioManager = TraeAudioManager.this;
                traeAudioManager.InternalSetSpeaker(traeAudioManager._context, TraeAudioManager.this._speakerOn);
            }
            updateStatus();
            if (!TraeAudioManager.IsUpdateSceneFlag) {
                QLog.w(TraeAudioManager.TAG, "connect earphone: do nothing");
                return;
            }
            while (this._running) {
                if (TraeAudioManager.this._am.isSpeakerphoneOn() != TraeAudioManager.this._speakerOn) {
                    TraeAudioManager traeAudioManager2 = TraeAudioManager.this;
                    traeAudioManager2.InternalSetSpeaker(traeAudioManager2._context, TraeAudioManager.this._speakerOn);
                }
                try {
                    Thread.sleep(i < 5 ? 1000L : 4000L);
                } catch (InterruptedException e) {
                }
                i++;
            }
        }

        @Override
        public String getDeviceName() {
            return TraeAudioManager.DEVICE_EARPHONE;
        }

        @Override
        public void _quit() {
        }
    }

    class speakerSwitchThread extends switchThread {
        speakerSwitchThread() {
            super();
        }

        @Override
        public void _run() {
            int i = 0;
            if (!TraeAudioManager.IsMusicScene && TraeAudioManager.IsUpdateSceneFlag) {
                TraeAudioManager traeAudioManager = TraeAudioManager.this;
                traeAudioManager.InternalSetSpeaker(traeAudioManager._context, TraeAudioManager.this._speakerOn);
            }
            updateStatus();
            if (TraeAudioManager.IsMusicScene || !TraeAudioManager.IsUpdateSceneFlag) {
                QLog.w(TraeAudioManager.TAG, "connect speakerPhone: do nothing");
                return;
            }
            QLog.w(TraeAudioManager.TAG, " _run:" + getDeviceName() + " _running:" + this._running);
            while (this._running) {
                try {
                    if (TraeAudioManager.this._am.isSpeakerphoneOn() != TraeAudioManager.this._speakerOn) {
                        TraeAudioManager.this.InternalSetSpeaker(TraeAudioManager.this._context, TraeAudioManager.this._speakerOn);
                    }
                } catch (Exception e) {
                }
                try {
                    Thread.sleep(i < 5 ? 1000L : 4000L);
                } catch (InterruptedException e2) {
                }
                i++;
            }
        }

        @Override
        public String getDeviceName() {
            return TraeAudioManager.DEVICE_SPEAKERPHONE;
        }

        @Override
        public void _quit() {
        }
    }

    class headsetSwitchThread extends switchThread {
        headsetSwitchThread() {
            super();
        }

        @Override
        public void _run() {
            int i = 0;
            if (!TraeAudioManager.IsMusicScene && TraeAudioManager.IsUpdateSceneFlag) {
                TraeAudioManager traeAudioManager = TraeAudioManager.this;
                traeAudioManager.InternalSetSpeaker(traeAudioManager._context, false);
                TraeAudioManager.this._am.setWiredHeadsetOn(true);
            }
            updateStatus();
            if (TraeAudioManager.IsMusicScene || !TraeAudioManager.IsUpdateSceneFlag) {
                QLog.w(TraeAudioManager.TAG, "connect headset: do nothing");
                return;
            }
            while (this._running) {
                try {
                    if (TraeAudioManager.this._am.isSpeakerphoneOn()) {
                        TraeAudioManager.this.InternalSetSpeaker(TraeAudioManager.this._context, false);
                    }
                } catch (Exception e) {
                }
                try {
                    Thread.sleep(i < 5 ? 1000L : 4000L);
                } catch (InterruptedException e2) {
                }
                i++;
            }
        }

        @Override
        public String getDeviceName() {
            return TraeAudioManager.DEVICE_WIREDHEADSET;
        }

        @Override
        public void _quit() {
        }
    }

    class bluetoothHeadsetSwitchThread extends switchThread {
        bluetoothHeadsetSwitchThread() {
            super();
        }

        @Override
        public void _run() {
            if (TraeAudioManager.IsMusicScene || !TraeAudioManager.IsUpdateSceneFlag || TraeAudioManager.nSceneMode == 7) {
                QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread: do nothing, IsMusicScene:" + TraeAudioManager.IsMusicScene + " ,IsUpdateSceneFlag:" + TraeAudioManager.IsUpdateSceneFlag);
                updateStatus();
                return;
            }
            try {
                QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread sleep 1000");
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
            }
            if (TraeAudioManager.this.bluetoothState == 7) {
                QLog.w(TraeAudioManager.TAG, "WIREDHEADSET plugout, bluetoothState == Bluetooth_State.SCO_CONNECTED force to HEADSET_AVAILABLE, reconnect");
                TraeAudioManager.this.bluetoothState = 4;
            }
            int retryCount = 0;
            while (TraeAudioManager.this.bluetoothState != 4) {
                int retryCount2 = retryCount + 1;
                if (retryCount >= 10) {
                    break;
                }
                QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread waiting Bluetooth_State HEADSET_AVAILABLE, " + TraeAudioManager.this.bluetoothState);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e2) {
                }
                retryCount = retryCount2;
            }
            int retryCount3 = 0;
            boolean isBluetoothNeedStop = false;
            if (TraeAudioManager.this.bluetoothState != 4) {
                retryCount3 = 1;
            }
            if (retryCount3 == 0 && this._running) {
                TraeAudioManager.this.bluetoothState = 6;
                _startBluetoothSco();
                isBluetoothNeedStop = true;
                QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread _startBluetoothSco");
            }
            int i = 0;
            while (this._running) {
                int i2 = i + 1;
                if (i < 10 && retryCount3 == 0) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("bluetoothHeadsetSwitchThread i:");
                    sb.append(i2);
                    sb.append(" sco:");
                    sb.append(TraeAudioManager.this._am.isBluetoothScoOn() ? "Y" : "N");
                    sb.append(" :");
                    sb.append(TraeAudioManager.this._deviceConfigManager.getBluetoothName());
                    QLog.w(TraeAudioManager.TAG, sb.toString());
                    if (TraeAudioManager.this.bluetoothState == 7) {
                        QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread bluetoothState ==  Bluetooth_State.SCO_CONNECTED 1");
                        updateStatus();
                    } else {
                        try {
                            Thread.sleep(3000L);
                        } catch (InterruptedException e3) {
                        }
                        if (TraeAudioManager.this.bluetoothState == 7) {
                            QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread bluetoothState ==  Bluetooth_State.SCO_CONNECTED 2");
                            updateStatus();
                        } else {
                            if (isBluetoothNeedStop && this._running) {
                                _stopBluetoothSco();
                                try {
                                    Thread.sleep(1000L);
                                } catch (InterruptedException e4) {
                                }
                                _startBluetoothSco();
                                QLog.w(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread retry start sco");
                            }
                            i = i2;
                        }
                    }
                }
            }
            if (TraeAudioManager.this.bluetoothState != 7) {
                if (this._running && retryCount3 == 0) {
                    QLog.e(TraeAudioManager.TAG, "bluetoothHeadsetSwitchThread sco fail,remove btheadset");
                    TraeAudioManager.this._deviceConfigManager.setVisible(getDeviceName(), false);
                }
                processDeviceConnectRes(10);
                TraeAudioManager.this.checkAutoDeviceListUpdate();
            }
        }

        @Override
        public String getDeviceName() {
            return TraeAudioManager.DEVICE_BLUETOOTHHEADSET;
        }

        @Override
        public void _quit() {
            if (TraeAudioManager.this._am == null) {
                return;
            }
            _stopBluetoothSco();
        }

        void _startBluetoothSco() {
            try {
                TraeAudioManager.this._am.setBluetoothScoOn(true);
                if (ClientInfo.VERSION_SDK_INT > 8) {
                    TraeAudioManager.this._am.startBluetoothSco();
                }
            } catch (Exception e) {
            }
        }

        void _stopBluetoothSco() {
            if (ClientInfo.VERSION_SDK_INT > 8) {
                TraeAudioManager.this._am.stopBluetoothSco();
            }
            TraeAudioManager.this._am.setBluetoothScoOn(false);
        }
    }

    int InternalSessionIsDeviceChangabled(HashMap<String, Object> params) {
        Intent intent = new Intent();
        intent.putExtra(ISDEVICECHANGABLED_RESULT_ISCHANGABLED, InternalIsDeviceChangeable());
        sendResBroadcast(intent, params, 0);
        return 0;
    }

    boolean InternalIsDeviceChangeable() {
        String str = this._deviceConfigManager.getConnectingDevice();
        if (str == null || str.equals(DEVICE_NONE) || str.equals("")) {
            return true;
        }
        return false;
    }

    int InternalSessionGetConnectedDevice(HashMap<String, Object> params) {
        Intent intent = new Intent();
        intent.putExtra(GETCONNECTEDDEVICE_RESULT_LIST, this._deviceConfigManager.getConnectedDevice());
        sendResBroadcast(intent, params, 0);
        return 0;
    }

    int InternalSessionGetConnectingDevice(HashMap<String, Object> params) {
        Intent intent = new Intent();
        intent.putExtra(GETCONNECTINGDEVICE_RESULT_LIST, this._deviceConfigManager.getConnectingDevice());
        sendResBroadcast(intent, params, 0);
        return 0;
    }

    int sendResBroadcast(final Intent intent, HashMap<String, Object> params, final int err) {
        if (this._context == null) {
            return -1;
        }
        Long sid = (Long) params.get(PARAM_SESSIONID);
        QLog.w(TAG, " sessonID:" + sid + " " + ((String) params.get(PARAM_OPERATION)));
        if (sid == null || sid.longValue() == Long.MIN_VALUE) {
            InternalNotifyDeviceListUpdate();
            QLog.e(TAG, "sendResBroadcast sid null,don't send res");
            return -1;
        }
        final Long TAMSessionId = (Long) params.get(PARAM_SESSIONID);
        final String TAMOperation = (String) params.get(PARAM_OPERATION);
        if (OPERATION_VOICECALL_PREPROCESS.equals(TAMOperation)) {
            intent.setAction(ACTION_TRAEAUDIOMANAGER_RES);
            intent.putExtra(PARAM_SESSIONID, TAMSessionId);
            intent.putExtra(PARAM_OPERATION, TAMOperation);
            intent.putExtra(PARAM_RES_ERRCODE, err);
            TraeAudioSessionHost traeAudioSessionHost = this._audioSessionHost;
            if (traeAudioSessionHost != null) {
                traeAudioSessionHost.sendToAudioSessionMessage(intent);
                return 0;
            }
            return 0;
        }
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                intent.setAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_RES);
                intent.putExtra(TraeAudioManager.PARAM_SESSIONID, TAMSessionId);
                intent.putExtra(TraeAudioManager.PARAM_OPERATION, TAMOperation);
                intent.putExtra(TraeAudioManager.PARAM_RES_ERRCODE, err);
                if (TraeAudioManager.this._context != null) {
                    TraeAudioManager.this._context.sendBroadcast(intent);
                }
            }
        });
        return 0;
    }

    int InternalNotifyDeviceListUpdate() {
        AudioDeviceInterface.LogTraceEntry("");
        if (this._context == null) {
            return -1;
        }
        HashMap<String, Object> params = this._deviceConfigManager.getSnapParams();
        final ArrayList<String> list = (ArrayList) params.get(EXTRA_DATA_AVAILABLEDEVICE_LIST);
        final String con = (String) params.get(EXTRA_DATA_CONNECTEDDEVICE);
        final String prevCon = (String) params.get(EXTRA_DATA_PREV_CONNECTEDDEVICE);
        final String _bluetoothName = this._deviceConfigManager.getBluetoothName();
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_NOTIFY);
                intent.putExtra(TraeAudioManager.PARAM_OPERATION, TraeAudioManager.NOTIFY_DEVICELIST_UPDATE);
                intent.putExtra(TraeAudioManager.EXTRA_DATA_AVAILABLEDEVICE_LIST, (String[]) list.toArray(new String[0]));
                intent.putExtra(TraeAudioManager.EXTRA_DATA_CONNECTEDDEVICE, con);
                intent.putExtra(TraeAudioManager.EXTRA_DATA_PREV_CONNECTEDDEVICE, prevCon);
                intent.putExtra(TraeAudioManager.EXTRA_DATA_IF_HAS_BLUETOOTH_THIS_IS_NAME, _bluetoothName);
                if (TraeAudioManager.this._context != null) {
                    TraeAudioManager.this._context.sendBroadcast(intent);
                }
            }
        });
        AudioDeviceInterface.LogTraceExit();
        return 0;
    }

    int InternalNotifyDeviceChangableUpdate() {
        if (this._context == null) {
            return -1;
        }
        final boolean TAMisDeviceChangeable = InternalIsDeviceChangeable();
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setAction(TraeAudioManager.ACTION_TRAEAUDIOMANAGER_NOTIFY);
                intent.putExtra(TraeAudioManager.PARAM_OPERATION, TraeAudioManager.NOTIFY_DEVICECHANGABLE_UPDATE);
                intent.putExtra(TraeAudioManager.NOTIFY_DEVICECHANGABLE_UPDATE_DATE, TAMisDeviceChangeable);
                if (TraeAudioManager.this._context != null) {
                    TraeAudioManager.this._context.sendBroadcast(intent);
                }
            }
        });
        return 0;
    }

    abstract class BluetoohHeadsetCheckInterface {
        abstract void _addAction(IntentFilter intentFilter);

        abstract void _onReceive(Context context, Intent intent);

        public abstract boolean init(Context context, DeviceConfigManager deviceConfigManager);

        public abstract String interfaceDesc();

        public abstract boolean isConnected();

        public abstract void release();

        BluetoohHeadsetCheckInterface() {
        }

        public void addAction(IntentFilter filter) {
            filter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
            filter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
            filter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
            _addAction(filter);
        }

        public void onReceive(Context context, Intent intent, DeviceConfigManager devCfg) {
            QLog.w(TraeAudioManager.TAG, interfaceDesc() + " onReceive|" + intent.getAction());
            if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(intent.getAction())) {
                int state = intent.getIntExtra("android.bluetooth.adapter.extra.STATE", -1);
                int pre_state = intent.getIntExtra("android.bluetooth.adapter.extra.PREVIOUS_STATE", -1);
                QLog.i(TraeAudioManager.TAG, String.format("bluetooth onReceive|state=%d, pre_state=%d", Integer.valueOf(state), Integer.valueOf(pre_state)));
                if (state == 10) {
                    QLog.w(TraeAudioManager.TAG, "    BT off");
                    devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                    return;
                } else {
                    if (state == 12) {
                        getProfile();
                        return;
                    }
                    return;
                }
            }
            if (!"android.bluetooth.device.action.ACL_CONNECTED".equals(intent.getAction()) || ClientInfo.VERSION_SDK_INT >= 11) {
                if (!"android.bluetooth.device.action.ACL_DISCONNECTED".equals(intent.getAction()) || ClientInfo.VERSION_SDK_INT >= 11) {
                    _onReceive(context, intent);
                }
            }
        }

        String getBTActionStateChangedExtraString(int state) {
            String valuestr;
            switch (state) {
                case 10:
                    valuestr = "OFF";
                    break;
                case 11:
                    valuestr = "TURNING_ON";
                    break;
                case 12:
                    valuestr = "ON";
                    break;
                case 13:
                    valuestr = "TURNING_OFF";
                    break;
                default:
                    valuestr = "unknow";
                    break;
            }
            return valuestr + ":" + state;
        }

        String getSCOAudioState(int state) {
            String valuestr;
            if (state == -1) {
                valuestr = "ERROR";
            } else if (state == 0) {
                valuestr = "DISCONNECTED";
            } else if (state == 1) {
                valuestr = "CONNECTED";
            } else if (state == 2) {
                valuestr = "CONNECTING";
            } else {
                valuestr = "unknow";
            }
            return valuestr + ":" + state;
        }

        String getBTAdapterConnectionState(int state) {
            String valuestr;
            if (state == 0) {
                valuestr = "DISCONNECTED";
            } else if (state == 1) {
                valuestr = "CONNECTING";
            } else if (state == 2) {
                valuestr = "CONNECTED";
            } else if (state == 3) {
                valuestr = "DISCONNECTING";
            } else {
                valuestr = "unknow";
            }
            return valuestr + ":" + state;
        }

        boolean getProfile() {
            return true;
        }

        String getBTHeadsetConnectionState(int state) {
            String valuestr;
            if (state == 0) {
                valuestr = "DISCONNECTED";
            } else if (state == 1) {
                valuestr = "CONNECTING";
            } else if (state == 2) {
                valuestr = "CONNECTED";
            } else if (state == 3) {
                valuestr = "DISCONNECTING";
            } else {
                valuestr = "unknow";
            }
            return valuestr + ":" + state;
        }

        String getBTHeadsetAudioState(int state) {
            String valuestr;
            switch (state) {
                case 10:
                    valuestr = "DISCONNECTED";
                    break;
                case 11:
                    valuestr = "CONNECTING";
                    break;
                case 12:
                    valuestr = "CONNECTED";
                    break;
                default:
                    valuestr = "unknow:" + state;
                    break;
            }
            return valuestr + ":" + state;
        }

        String getBluetoothDeviceName(BluetoothDevice dev) {
            if (dev == null) {
                return " ";
            }
            try {
                return dev.getName();
            } catch (Exception e) {
                QLog.e(TraeAudioManager.TAG, "BluetoothDevice getName fail.", e);
                return " ";
            }
        }
    }

    class BluetoohHeadsetCheckFake extends BluetoohHeadsetCheckInterface {
        BluetoohHeadsetCheckFake() {
            super();
        }

        @Override
        public boolean init(Context ctx, DeviceConfigManager devCfg) {
            return true;
        }

        @Override
        public void release() {
        }

        @Override
        public boolean isConnected() {
            return false;
        }

        @Override
        void _addAction(IntentFilter filter) {
        }

        @Override
        void _onReceive(Context context, Intent intent) {
        }

        @Override
        public String interfaceDesc() {
            return "BluetoohHeadsetCheckFake";
        }
    }

    public BluetoohHeadsetCheckInterface CreateBluetoothCheck(Context context, DeviceConfigManager devCfg) {
        BluetoohHeadsetCheckInterface intf = new BluetoohHeadsetCheck();
        if (!intf.init(context, devCfg)) {
            intf = new BluetoohHeadsetCheckFake();
        }
        QLog.w(TAG, "CreateBluetoothCheck:" + intf.interfaceDesc());
        return intf;
    }

    class BluetoohHeadsetCheck extends BluetoohHeadsetCheckInterface implements BluetoothProfile.ServiceListener {
        BluetoothAdapter _adapter;
        Context _ctx;
        DeviceConfigManager _devCfg;
        BluetoothProfile _profile;
        private final ReentrantLock _profileLock;

        BluetoohHeadsetCheck() {
            super();
            this._ctx = null;
            this._devCfg = null;
            this._adapter = null;
            this._profile = null;
            this._profileLock = new ReentrantLock();
        }

        @Override
        public boolean init(Context ctx, DeviceConfigManager devCfg) {
            AudioDeviceInterface.LogTraceEntry("");
            if (ctx == null || devCfg == null) {
                QLog.e(TraeAudioManager.TAG, " err ctx==null||_devCfg==null");
                return false;
            }
            this._ctx = ctx;
            this._devCfg = devCfg;
            boolean ret = getProfile();
            AudioDeviceInterface.LogTraceExit();
            return ret;
        }

        @Override
        boolean getProfile() {
            boolean ret = false;
            this._profileLock.lock();
            if (this._profile != null) {
                ret = true;
            } else {
                BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
                this._adapter = defaultAdapter;
                if (defaultAdapter == null) {
                    QLog.e(TraeAudioManager.TAG, "getDefaultAdapter fail!");
                } else if (!defaultAdapter.isEnabled()) {
                    QLog.e(TraeAudioManager.TAG, " BluetoothAdapter is not enable!");
                    ret = true;
                } else if (this._profile == null && !this._adapter.getProfileProxy(this._ctx, this, 1)) {
                    QLog.e(TraeAudioManager.TAG, "getProfileProxy HEADSET fail!");
                } else {
                    ret = true;
                }
            }
            this._profileLock.unlock();
            return ret;
        }

        @Override
        public void release() {
            this._profileLock.lock();
            AudioDeviceInterface.LogTraceEntry("_profile:" + this._profile);
            try {
                try {
                    if (this._adapter != null) {
                        if (this._profile != null) {
                            this._adapter.closeProfileProxy(1, this._profile);
                        }
                        this._profile = null;
                    }
                } catch (Exception e) {
                    QLog.w(TraeAudioManager.TAG, " closeProfileProxy:e:" + e.getMessage());
                }
                AudioDeviceInterface.LogTraceExit();
            } finally {
                this._profileLock.unlock();
            }
        }

        @Override
        public boolean isConnected() {
            boolean bc = false;
            this._profileLock.lock();
            try {
                try {
                    if (this._profile != null) {
                        List<BluetoothDevice> devs = this._profile.getConnectedDevices();
                        if (devs == null) {
                            return false;
                        }
                        bc = devs.size() > 0;
                    }
                } catch (Exception e) {
                    QLog.e(TraeAudioManager.TAG, "getConnectedDevices fail.", e);
                }
                return bc;
            } finally {
                this._profileLock.unlock();
            }
        }

        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == 1) {
                this._profileLock.lock();
                AudioDeviceInterface.LogTraceEntry("_profile:" + this._profile + " profile:" + profile + " proxy:" + proxy);
                try {
                    try {
                        if (this._profile != null && this._profile != proxy) {
                            QLog.w(TraeAudioManager.TAG, "BluetoohHeadsetCheck: HEADSET Connected proxy:" + proxy + " _profile:" + this._profile);
                            this._adapter.closeProfileProxy(1, this._profile);
                            this._profile = null;
                        }
                        this._profile = proxy;
                        List<BluetoothDevice> devs = null;
                        if (proxy != null) {
                            devs = proxy.getConnectedDevices();
                        }
                        if (devs != null && this._profile != null) {
                            QLog.w(TraeAudioManager.TAG, "TRAEBluetoohProxy: HEADSET Connected devs:" + devs.size() + " _profile:" + this._profile);
                            for (int i = 0; i < devs.size(); i++) {
                                BluetoothDevice d = devs.get(i);
                                int state = 0;
                                try {
                                    if (this._profile != null) {
                                        state = this._profile.getConnectionState(d);
                                    }
                                } catch (Exception e) {
                                    QLog.e(TraeAudioManager.TAG, "getConnectionState fail.", e);
                                }
                                if (state == 2) {
                                    this._devCfg.setBluetoothName(getBluetoothDeviceName(d));
                                }
                                QLog.i(TraeAudioManager.TAG, "   " + i + " " + getBluetoothDeviceName(d) + " ConnectionState:" + state);
                            }
                        }
                    } catch (Exception e2) {
                        QLog.e(TraeAudioManager.TAG, "getConnectedDevices fail.", e2);
                    }
                    this._profileLock.unlock();
                    if (this._devCfg != null) {
                        String bluetoothName = null;
                        if (TraeAudioManager.this._deviceConfigManager != null) {
                            bluetoothName = TraeAudioManager.this._deviceConfigManager.getBluetoothName();
                        }
                        if (TextUtils.isEmpty(bluetoothName)) {
                            this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                        } else if (isConnected()) {
                            this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, true);
                            TraeAudioManager.this.checkDevicePlug(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, true);
                        } else {
                            this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                        }
                    }
                    AudioDeviceInterface.LogTraceExit();
                } catch (Throwable th) {
                    this._profileLock.unlock();
                    throw th;
                }
            }
        }

        @Override
        public void onServiceDisconnected(int profile) {
            if (profile == 1) {
                QLog.w(TraeAudioManager.TAG, "TRAEBluetoohProxy: HEADSET Disconnected");
                if (isConnected()) {
                    TraeAudioManager.this.checkDevicePlug(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                }
                this._profileLock.lock();
                AudioDeviceInterface.LogTraceEntry("_profile:" + this._profile + " profile:" + profile);
                try {
                    if (this._profile != null) {
                        this._adapter.closeProfileProxy(1, this._profile);
                        this._profile = null;
                    }
                    this._profileLock.unlock();
                    AudioDeviceInterface.LogTraceExit();
                } catch (Throwable th) {
                    this._profileLock.unlock();
                    throw th;
                }
            }
        }

        @Override
        void _addAction(IntentFilter filter) {
            QLog.w(TraeAudioManager.TAG, " " + interfaceDesc() + " _addAction");
            filter.addAction("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED");
            filter.addAction("android.media.ACTION_SCO_AUDIO_STATE_UPDATED");
            filter.addAction("android.bluetooth.headset.profile.action.AUDIO_STATE_CHANGED");
            filter.addAction("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED");
        }

        @Override
        void _onReceive(Context context, Intent intent) {
            QLog.i(TraeAudioManager.TAG, interfaceDesc() + " _onReceive action=" + intent.getAction());
            if ("android.bluetooth.headset.profile.action.AUDIO_STATE_CHANGED".equals(intent.getAction())) {
                int state = intent.getIntExtra("android.bluetooth.profile.extra.STATE", -1);
                int pre_state = intent.getIntExtra("android.bluetooth.profile.extra.PREVIOUS_STATE", -1);
                QLog.i(TraeAudioManager.TAG, interfaceDesc() + String.format(" _onReceive|state=%s, pre_state=%s, dev=%s", getBTHeadsetAudioState(state), getBTHeadsetAudioState(pre_state), getBluetoothDeviceName((BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"))));
                if (state == 12 && TraeAudioManager.this.bluetoothState == 6) {
                    QLog.w(TraeAudioManager.TAG, interfaceDesc() + " _onReceive|SCO is connected");
                    TraeAudioManager.this.bluetoothState = 7;
                    return;
                }
                return;
            }
            if ("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED".equals(intent.getAction())) {
                int state2 = intent.getIntExtra("android.bluetooth.profile.extra.STATE", -1);
                int pre_state2 = intent.getIntExtra("android.bluetooth.profile.extra.PREVIOUS_STATE", -1);
                QLog.i(TraeAudioManager.TAG, interfaceDesc() + String.format(" _onReceive|state=%s, pre_state=%s, dev=%s", getBTHeadsetConnectionState(state2), getBTHeadsetConnectionState(pre_state2), getBluetoothDeviceName((BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"))));
                if (state2 == 0) {
                    TraeAudioManager.this.bluetoothState = 3;
                    this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                    return;
                } else {
                    if (state2 == 2) {
                        if (TraeAudioManager.this.bluetoothState == 3) {
                            TraeAudioManager.this.bluetoothState = 4;
                        }
                        this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, true);
                        return;
                    }
                    return;
                }
            }
            if ("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED".equals(intent.getAction())) {
                int state3 = intent.getIntExtra("android.bluetooth.adapter.extra.CONNECTION_STATE", -1);
                int pre_state3 = intent.getIntExtra("android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE", -1);
                BluetoothDevice dev = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                QLog.i(TraeAudioManager.TAG, interfaceDesc() + String.format(" _onReceive|state=%s, pre_state=%s, dev=%s", getBTAdapterConnectionState(state3), getBTAdapterConnectionState(pre_state3), getBluetoothDeviceName(dev)));
                if (state3 == 2) {
                    this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, true);
                    this._devCfg.setBluetoothName(getBluetoothDeviceName(dev));
                    return;
                } else {
                    if (state3 == 0) {
                        this._devCfg.setVisible(TraeAudioManager.DEVICE_BLUETOOTHHEADSET, false);
                        return;
                    }
                    return;
                }
            }
            if ("android.media.ACTION_SCO_AUDIO_STATE_UPDATED".equals(intent.getAction())) {
                int state4 = intent.getIntExtra("android.media.extra.SCO_AUDIO_STATE", -1);
                int pre_state4 = intent.getIntExtra("android.media.extra.SCO_AUDIO_PREVIOUS_STATE", -1);
                QLog.i(TraeAudioManager.TAG, interfaceDesc() + String.format(" _onReceive|state=%s, pre_state=%s", getSCOAudioState(state4), getSCOAudioState(pre_state4)));
            }
        }

        @Override
        public String interfaceDesc() {
            return "BluetoohHeadsetCheck";
        }
    }

    static String getForceConfigName(int config) {
        if (config < 0) {
            return "unknow";
        }
        String[] strArr = forceName;
        if (config < strArr.length) {
            return strArr[config];
        }
        return "unknow";
    }

    public static Object invokeMethod(Object owner, String methodName, Object[] args, Class[] argsClass) {
        try {
            Class ownerClass = owner.getClass();
            Method method = ownerClass.getMethod(methodName, argsClass);
            Object res = method.invoke(owner, args);
            return res;
        } catch (Exception e) {
            QLog.w(TAG, "invokeMethod Exception:" + e.getMessage());
            return null;
        }
    }

    public static Object invokeStaticMethod(String className, String methodName, Object[] args, Class[] argsClass) {
        try {
            Class ownerClass = Class.forName(className);
            Method method = ownerClass.getMethod(methodName, argsClass);
            Object res = method.invoke(null, args);
            return res;
        } catch (ClassNotFoundException e) {
            QLog.w(TAG, "ClassNotFound:" + className);
            return null;
        } catch (IllegalAccessException e2) {
            QLog.w(TAG, "IllegalAccess:" + methodName);
            return null;
        } catch (IllegalArgumentException e3) {
            QLog.w(TAG, "IllegalArgument:" + methodName);
            return null;
        } catch (NoSuchMethodException e4) {
            QLog.w(TAG, "NoSuchMethod:" + methodName);
            return null;
        } catch (InvocationTargetException e5) {
            QLog.w(TAG, "InvocationTarget:" + methodName);
            return null;
        } catch (Exception e6) {
            QLog.w(TAG, "invokeStaticMethod Exception:" + e6.getMessage());
            return null;
        }
    }

    static void setParameters(String keyValuePairs) {
        Object[] args = {keyValuePairs};
        Class[] argsClass = new Class[args.length];
        argsClass[0] = String.class;
        QLog.w(TAG, "setParameters  :" + keyValuePairs);
        invokeStaticMethod("android.media.AudioSystem", "setParameters", args, argsClass);
    }

    static void setPhoneState(int state) {
        Object[] args = {Integer.valueOf(state)};
        Class[] argsClass = new Class[args.length];
        argsClass[0] = Integer.TYPE;
        invokeStaticMethod("android.media.AudioSystem", "setPhoneState", args, argsClass);
    }

    static void setForceUse(int usage, int config) {
        Object[] args = {Integer.valueOf(usage), Integer.valueOf(config)};
        Class[] argsClass = new Class[args.length];
        argsClass[0] = Integer.TYPE;
        argsClass[1] = Integer.TYPE;
        Object res = invokeStaticMethod("android.media.AudioSystem", "setForceUse", args, argsClass);
        QLog.w(TAG, "setForceUse  usage:" + usage + " config:" + config + " ->" + getForceConfigName(config) + " res:" + res);
    }

    static int getForceUse(int usage) {
        Integer config = 0;
        Object[] args = {Integer.valueOf(usage)};
        Class[] argsClass = new Class[args.length];
        argsClass[0] = Integer.TYPE;
        Object value = invokeStaticMethod("android.media.AudioSystem", "getForceUse", args, argsClass);
        if (value != null) {
            config = (Integer) value;
        }
        QLog.w(TAG, "getForceUse  usage:" + usage + " config:" + config + " ->" + getForceConfigName(config.intValue()));
        return config.intValue();
    }

    static void forceVolumeControlStream(AudioManager am, int streamType) {
        if (ClientInfo.MANUFACTURER.equals("Google")) {
            QLog.w(TAG, "forceVolumeControlStream, Google phone nothing to do");
            return;
        }
        Object[] args = {Integer.valueOf(streamType)};
        Class[] argsClass = new Class[args.length];
        argsClass[0] = Integer.TYPE;
        Object res = invokeMethod(am, "forceVolumeControlStream", args, argsClass);
        QLog.w(TAG, "forceVolumeControlStream  streamType:" + streamType + " res:" + res);
    }
}