package com.cooleshow.base.utils;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class HeadsetPlugReceiver extends BroadcastReceiver {

    private HeadsetPlugListener mHeadsetPlugListener;

    public HeadsetPlugReceiver(HeadsetPlugListener headsetPlugListener) {
        this.mHeadsetPlugListener = headsetPlugListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //判断是否有蓝牙设备连接
        if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                @SuppressLint("MissingPermission") int state = adapter.getProfileConnectionState(BluetoothProfile.HEADSET);
                if (BluetoothProfile.STATE_CONNECTED == state) {
                    mHeadsetPlugListener.onHeadsetPlug(true,"蓝牙耳机");
                }
                if (BluetoothProfile.STATE_DISCONNECTED == state) {
                    mHeadsetPlugListener.onHeadsetPlug(false, "蓝牙耳机");
                }
            }
            //判断是否有有线耳机连接
        } else if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {
                    // 外放
                    mHeadsetPlugListener.onHeadsetPlug(false, "有线耳机");
                } else if (intent.getIntExtra("state", 0) == 1) {
                    // 耳机
                    mHeadsetPlugListener.onHeadsetPlug(true, "有线耳机");
                }
            }
        }
    }
}
