Java Code Examples for android.bluetooth.BluetoothHeadset

The following examples show how to use android.bluetooth.BluetoothHeadset. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void startBluetooth() {
	if (isBluetoothConnected) {
		Log.e("[Bluetooth] Already started, skipping...");
		return;
	}
	
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
		if (mProfileListener != null) {
			Log.w("[Bluetooth] Headset profile was already opened, let's close it");
			mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		}
		
		mProfileListener = new BluetoothProfile.ServiceListener() {
			public void onServiceConnected(int profile, BluetoothProfile proxy) {
			    if (profile == BluetoothProfile.HEADSET) {
			        Log.d("[Bluetooth] Headset connected");
			        mBluetoothHeadset = (BluetoothHeadset) proxy;
			        isBluetoothConnected = true;
			    }
			}
			public void onServiceDisconnected(int profile) {
			    if (profile == BluetoothProfile.HEADSET) {
			        mBluetoothHeadset = null;
			        isBluetoothConnected = false;
			        Log.d("[Bluetooth] Headset disconnected");
			        LinphoneManager.getInstance().routeAudioToReceiver();
			    }
			}
		};
		boolean success = mBluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
		if (!success) {
			Log.e("[Bluetooth] getProfileProxy failed !");
		}
	} else {
		Log.w("[Bluetooth] Interface disabled on device");
	}
}
 
Example 2
public BluetoothStateManager(@NonNull Context context, @Nullable BluetoothStateListener listener) {
  this.context                     = context.getApplicationContext();
  this.bluetoothAdapter            = BluetoothAdapter.getDefaultAdapter();
  this.bluetoothScoReceiver        = new BluetoothScoReceiver();
  this.bluetoothConnectionReceiver = new BluetoothConnectionReceiver();
  this.listener                    = listener;
  this.destroyed                   = new AtomicBoolean(false);

  if (this.bluetoothAdapter == null)
    return;

  requestHeadsetProxyProfile();

  this.context.registerReceiver(bluetoothConnectionReceiver, new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));

  Intent sticky = this.context.registerReceiver(bluetoothScoReceiver, new IntentFilter(getScoChangeIntent()));

  if (sticky != null) {
    bluetoothScoReceiver.onReceive(context, sticky);
  }

  handleBluetoothStateChange();
}
 
Example 3
public BluetoothStateManager(@NonNull Context context, @Nullable BluetoothStateListener listener) {
    this.context = context.getApplicationContext();
    this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (this.bluetoothAdapter == null) {
        return;
    }

    this.bluetoothScoReceiver = new BluetoothScoReceiver();
    this.bluetoothConnectionReceiver = new BluetoothConnectionReceiver();
    this.listener = listener;
    requestHeadsetProxyProfile();

    this.context.registerReceiver(bluetoothConnectionReceiver, new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));

    Intent sticky = this.context.registerReceiver(bluetoothScoReceiver, new IntentFilter(getScoChangeIntent()));
    if (sticky != null) {
        bluetoothScoReceiver.onReceive(this.context, sticky);
    }

    handleBluetoothStateChange();
}
 
Example 4
public void initBluetooth() {
	if (!ensureInit()) {
		Log.w("[Bluetooth] Manager tried to init bluetooth but LinphoneService not ready yet...");
		return;
	}
	
	IntentFilter filter = new IntentFilter();
	filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "." + BluetoothAssignedNumbers.PLANTRONICS);
	filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
	filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
	filter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
	mContext.registerReceiver(this,  filter);
	Log.d("[Bluetooth] Receiver started");
	
	startBluetooth();
}
 
Example 5
public boolean isBluetoothHeadsetAvailable() {
	ensureInit();
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() && mAudioManager != null && mAudioManager.isBluetoothScoAvailableOffCall()) {
		boolean isHeadsetConnected = false;
		if (mBluetoothHeadset != null) {
			List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
			mBluetoothDevice = null;
			for (final BluetoothDevice dev : devices) {    
				if (mBluetoothHeadset.getConnectionState(dev) == BluetoothHeadset.STATE_CONNECTED) {
					mBluetoothDevice = dev;
					isHeadsetConnected = true;
					break;
				}
			}
			Log.d(isHeadsetConnected ? "[Bluetooth] Headset found, bluetooth audio route available" : "[Bluetooth] No headset found, bluetooth audio route unavailable");
		}
		return isHeadsetConnected;
	}
	
	return false;
}
 
Example 6
Source Project: imsdk-android   Source File: AppRTCBluetoothManager.java    License: MIT License 5 votes vote down vote up
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
  if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
    return;
  }
  LogUtil.d(TAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
  // Android only supports one connected Bluetooth Headset at a time.
  bluetoothHeadset = (BluetoothHeadset) proxy;
  updateAudioDeviceState();
  LogUtil.d(TAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 7
Source Project: flutter-incall-manager   Source File: AppRTCBluetoothManager.java    License: ISC License 5 votes vote down vote up
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
  if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
    return;
  }
  Log.d(TAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
  // Android only supports one connected Bluetooth Headset at a time.
  bluetoothHeadset = (BluetoothHeadset) proxy;
  updateAudioDeviceState();
  Log.d(TAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 8
Source Project: ClassicBluetooth   Source File: BluetoothReceiver.java    License: Apache License 2.0 5 votes vote down vote up
public BluetoothReceiver(Context context, BaseConfigCallback callback) {
    mCallback = callback;
    IntentFilter filter = new IntentFilter();
    //蓝牙开关状态
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    //蓝牙开始搜索
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    //蓝牙搜索结束
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    //蓝牙发现新设备(未配对)
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    //设备配对状态改变
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    //设备建立连接
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    //设备断开连接
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

    //BluetoothAdapter连接状态
    filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
    //BluetoothHeadset连接状态
    filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    //BluetoothA2dp连接状态
    filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);

    context.registerReceiver(this, filter);
}
 
Example 9
Source Project: AssistantBySDK   Source File: AssistantService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
    Log.e("blueHeadsetListener", "onServiceConnected:" + profile);
    if (profile == BluetoothProfile.A2DP) {
        voiceMediator.setBluetoothA2dp((BluetoothA2dp) proxy);
    } else if (profile == BluetoothProfile.HEADSET) {
        voiceMediator.setBluetoothHeadset((BluetoothHeadset) proxy);
    }
}
 
Example 10
Source Project: AssistantBySDK   Source File: VoiceMediator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startBluetoothSco() {
    if (isBlueToothHeadSet()) {
        BluetoothHeadset headset = getBluetoothHeadset();
        if (headset == null || headset.getConnectedDevices().isEmpty() || headset.isAudioConnected(headset.getConnectedDevices().get(0)))
            return;
        Log.e(TAG, "startBluetoothSco:device size=" + headset.getConnectedDevices().size());
        headset.startVoiceRecognition(headset.getConnectedDevices().get(0));
    }
}
 
Example 11
Source Project: apollo-DuerOS   Source File: BtNativeInterface.java    License: Apache License 2.0 5 votes vote down vote up
private void registerReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(BtUtils.ACTION_PAIRING_REQUEST);
    filter.addAction(BtUtils.ACTION_BOND_STATE_CHANGED);
    filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    if (mContext != null) {
        mContext.registerReceiver(mBluetoothReceiver, filter);
    }
}
 
Example 12
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
  if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
    return;
  }
  Log.d(TAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
  // Android only supports one connected Bluetooth Headset at a time.
  bluetoothHeadset = (BluetoothHeadset) proxy;
  updateAudioDeviceState();
  Log.d(TAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 13
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
    if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
        return;
    }
    Log.d(Config.LOGTAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
    // Android only supports one connected Bluetooth Headset at a time.
    bluetoothHeadset = (BluetoothHeadset) proxy;
    updateAudioDeviceState();
    Log.d(Config.LOGTAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 14
Source Project: opentok-android-sdk-samples   Source File: CustomAudioDevice.java    License: MIT License 5 votes vote down vote up
private void registerBtReceiver() {
    if (!scoReceiverRegistered) {
        context.registerReceiver(
            btStatusReceiver,
            new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
        );
        scoReceiverRegistered = true;
    }
}
 
Example 15
Source Project: opentok-android-sdk-samples   Source File: CustomAudioDevice.java    License: MIT License 5 votes vote down vote up
private void disableBluetoothEvents() {
    if (null != bluetoothProfile && bluetoothAdapter != null) {
        bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothProfile);
    }
    unregisterBtReceiver();
    /* force a shutdown of bluetooth: when a call comes in, the handler is not invoked by system */
    Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    intent.putExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED);
    btStatusReceiver.onReceive(context, intent);
}
 
Example 16
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
    if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
        return;
    }
    Log.d(Config.LOGTAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
    // Android only supports one connected Bluetooth Headset at a time.
    bluetoothHeadset = (BluetoothHeadset) proxy;
    updateAudioDeviceState();
    Log.d(Config.LOGTAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 17
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)!=null) {
		int outFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
		VoIPController.setNativeBufferSize(outFramesPerBuffer);
	} else {
		VoIPController.setNativeBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
	}
	try {
		cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
		cpuWakelock.acquire();

		btAdapter=am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		if(!USE_CONNECTION_SERVICE){
			filter.addAction(ACTION_HEADSET_PLUG);
			if(btAdapter!=null){
				filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
				filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
			}
			filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		}
		registerReceiver(receiver, filter);

		soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
		spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
		spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
		spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
		spEndId = soundPool.load(this, R.raw.voip_end, 1);
		spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

		am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

		if(!USE_CONNECTION_SERVICE && btAdapter!=null && btAdapter.isEnabled()){
			int headsetState=btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
			updateBluetoothHeadsetState(headsetState==BluetoothProfile.STATE_CONNECTED);
			//if(headsetState==BluetoothProfile.STATE_CONNECTED)
			//	am.setBluetoothScoOn(true);
			for (StateListener l : stateListeners)
				l.onAudioSettingsChanged();
		}

	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 18
Source Project: imsdk-android   Source File: AppRTCBluetoothManager.java    License: MIT License 4 votes vote down vote up
/**
 * Activates components required to detect Bluetooth devices and to enable
 * BT SCO (audio is routed via BT SCO) for the headset profile. The end
 * state will be HEADSET_UNAVAILABLE but a state machine has started which
 * will start a state change sequence where the final outcome depends on
 * if/when the BT headset is enabled.
 * Example of state change sequence when start() is called while BT device
 * is connected and enabled:
 *   UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
 *   SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
 * Note that the AppRTCAudioManager is also involved in driving this state
 * change.
 */
public void start() {
  AppRTCUtils.checkIsOnMainThread(apprtcContext);

  LogUtil.d(TAG, "start");
  if (!hasPermission(apprtcContext, android.Manifest.permission.BLUETOOTH)) {
    Log.w(TAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
    return;
  }
  if (bluetoothState != State.UNINITIALIZED) {
    Log.w(TAG, "Invalid BT state");
    return;
  }
  bluetoothHeadset = null;
  bluetoothDevice = null;
  scoConnectionAttempts = 0;
  // Get a handle to the default local Bluetooth adapter.
  bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (bluetoothAdapter == null) {
    Log.w(TAG, "Device does not support Bluetooth");
    return;
  }
  // Ensure that the device supports use of BT SCO audio for off call use cases.
  if (!audioManager.isBluetoothScoAvailableOffCall()) {
    LogUtil.e(TAG, "Bluetooth SCO audio is not available off call");
    return;
  }
  logBluetoothAdapterInfo(bluetoothAdapter);
  // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
  // Hands-Free) proxy object and install a listener.
  if (!getBluetoothProfileProxy(
          apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
    LogUtil.e(TAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
    return;
  }
  // Register receivers for BluetoothHeadset change notifications.
  IntentFilter bluetoothHeadsetFilter = new IntentFilter();
  // Register receiver for change in connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
  // Register receiver for change in audio connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
  try {
    registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
  }catch (Exception ex)
  {
    LogUtil.e(ex.getMessage());
  }
  LogUtil.d(TAG, "HEADSET profile state: "
          + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
  LogUtil.d(TAG, "Bluetooth proxy for headset profile has started");
  bluetoothState = State.HEADSET_UNAVAILABLE;
  LogUtil.d(TAG, "start done: BT state=" + bluetoothState);
}
 
Example 19
Source Project: flutter-incall-manager   Source File: AppRTCBluetoothManager.java    License: ISC License 4 votes vote down vote up
/**
 * Activates components required to detect Bluetooth devices and to enable
 * BT SCO (audio is routed via BT SCO) for the headset profile. The end
 * state will be HEADSET_UNAVAILABLE but a state machine has started which
 * will start a state change sequence where the final outcome depends on
 * if/when the BT headset is enabled.
 * Example of state change sequence when start() is called while BT device
 * is connected and enabled:
 *   UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
 *   SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
 * Note that the IncallPlugin is also involved in driving this state
 * change.
 */
public void start() {
  Log.d(TAG, "start");
  if (!hasPermission(apprtcContext, android.Manifest.permission.BLUETOOTH)) {
    Log.w(TAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
    return;
  }
  if (bluetoothState != State.UNINITIALIZED) {
    Log.w(TAG, "Invalid BT state");
    return;
  }
  bluetoothHeadset = null;
  bluetoothDevice = null;
  scoConnectionAttempts = 0;
  // Get a handle to the default local Bluetooth adapter.
  bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (bluetoothAdapter == null) {
    Log.w(TAG, "Device does not support Bluetooth");
    return;
  }
  // Ensure that the device supports use of BT SCO audio for off call use cases.
  if (!audioManager.isBluetoothScoAvailableOffCall()) {
    Log.e(TAG, "Bluetooth SCO audio is not available off call");
    return;
  }
  logBluetoothAdapterInfo(bluetoothAdapter);
  // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
  // Hands-Free) proxy object and install a listener.
  if (!getBluetoothProfileProxy(
          apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
    Log.e(TAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
    return;
  }
  // Register receivers for BluetoothHeadset change notifications.
  IntentFilter bluetoothHeadsetFilter = new IntentFilter();
  // Register receiver for change in connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
  // Register receiver for change in audio connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
  registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
  Log.d(TAG, "HEADSET profile state: "
          + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
  Log.d(TAG, "Bluetooth proxy for headset profile has started");
  bluetoothState = State.HEADSET_UNAVAILABLE;
  Log.d(TAG, "start done: BT state=" + bluetoothState);
}
 
Example 20
Source Project: ClassicBluetooth   Source File: BluetoothReceiver.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    BluetoothDevice dev;
    int state;
    if (action == null) {
        return;
    }
    switch (action) {
        /**
         * 蓝牙开关状态
         * int STATE_OFF = 10; //蓝牙关闭
         * int STATE_ON = 12; //蓝牙打开
         * int STATE_TURNING_OFF = 13; //蓝牙正在关闭
         * int STATE_TURNING_ON = 11; //蓝牙正在打开
         */
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            mCallback.onStateSwitch(state);
            break;
        /**
         * 蓝牙开始搜索
         */
        case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
            CbtLogs.i("蓝牙开始搜索");
            break;
        /**
         * 蓝牙搜索结束
         */
        case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
            CbtLogs.i("蓝牙扫描结束");
            mCallback.onScanStop();
            break;
        /**
         * 发现新设备
         */
        case BluetoothDevice.ACTION_FOUND:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mCallback.onFindDevice(dev);
            break;
        /**
         * 设备配对状态改变
         * int BOND_NONE = 10; //配对没有成功
         * int BOND_BONDING = 11; //配对中
         * int BOND_BONDED = 12; //配对成功
         */
        case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            CbtLogs.i("设备配对状态改变:" + dev.getBondState());
            break;
        /**
         * 设备建立连接
         * int STATE_DISCONNECTED = 0; //未连接
         * int STATE_CONNECTING = 1; //连接中
         * int STATE_CONNECTED = 2; //连接成功
         */
        case BluetoothDevice.ACTION_ACL_CONNECTED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            CbtLogs.i("设备建立连接:" + dev.getBondState());
            mCallback.onConnect(dev);
            break;
        /**
         * 设备断开连接
         */
        case BluetoothDevice.ACTION_ACL_DISCONNECTED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // mCallback.onConnect(dev.getBondState(), dev);
            break;
        /**
         * 本地蓝牙适配器
         * BluetoothAdapter连接状态
         */
        case BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            CbtLogs.i("STATE: " + intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0));
            CbtLogs.i("BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());
            break;
        /**
         * 提供用于手机的蓝牙耳机支持
         * BluetoothHeadset连接状态
         */
        case BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            CbtLogs.i("STATE: " + intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, 0));
            CbtLogs.i("BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());
            break;
        /**
         * 定义高质量音频可以从一个设备通过蓝牙连接传输到另一个设备
         * BluetoothA2dp连接状态
         */
        case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
            dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            CbtLogs.i("STATE: " + intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, 0));
            CbtLogs.i("BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());
            break;
        default:
            break;
    }
}
 
Example 21
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)!=null) {
		int outFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
		VoIPController.setNativeBufferSize(outFramesPerBuffer);
	} else {
		VoIPController.setNativeBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
	}
	try {
		cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
		cpuWakelock.acquire();

		btAdapter=am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		if(!USE_CONNECTION_SERVICE){
			filter.addAction(ACTION_HEADSET_PLUG);
			if(btAdapter!=null){
				filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
				filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
			}
			filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		}
		registerReceiver(receiver, filter);

		soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
		spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
		spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
		spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
		spEndId = soundPool.load(this, R.raw.voip_end, 1);
		spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

		am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

		if(!USE_CONNECTION_SERVICE && btAdapter!=null && btAdapter.isEnabled()){
			int headsetState=btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
			updateBluetoothHeadsetState(headsetState==BluetoothProfile.STATE_CONNECTED);
			//if(headsetState==BluetoothProfile.STATE_CONNECTED)
			//	am.setBluetoothScoOn(true);
			for (StateListener l : stateListeners)
				l.onAudioSettingsChanged();
		}

	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 22
Source Project: AssistantBySDK   Source File: VoiceMediator.java    License: Apache License 2.0 4 votes vote down vote up
public void setBluetoothHeadset(BluetoothHeadset bluetoothHeadset) {
    this.bluetoothHeadset = bluetoothHeadset;
}
 
Example 23
Source Project: AssistantBySDK   Source File: VoiceMediator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BluetoothHeadset getBluetoothHeadset() {
    return bluetoothHeadset;
}
 
Example 24
/**
 * Activates components required to detect Bluetooth devices and to enable
 * BT SCO (audio is routed via BT SCO) for the headset profile. The end
 * state will be HEADSET_UNAVAILABLE but a state machine has started which
 * will start a state change sequence where the final outcome depends on
 * if/when the BT headset is enabled.
 * Example of state change sequence when start() is called while BT device
 * is connected and enabled:
 *   UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
 *   SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
 * Note that the AppRTCAudioManager is also involved in driving this state
 * change.
 */
public void start() {
  Log.d(TAG, "start");
  if (!hasPermission(apprtcContext, android.Manifest.permission.BLUETOOTH)) {
    Log.w(TAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
    return;
  }
  if (bluetoothState != State.UNINITIALIZED) {
    Log.w(TAG, "Invalid BT state");
    return;
  }
  bluetoothHeadset = null;
  bluetoothDevice = null;
  scoConnectionAttempts = 0;
  // Get a handle to the default local Bluetooth adapter.
  bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (bluetoothAdapter == null) {
    Log.w(TAG, "Device does not support Bluetooth");
    return;
  }
  // Ensure that the device supports use of BT SCO audio for off call use cases.
  if (!audioManager.isBluetoothScoAvailableOffCall()) {
    Log.e(TAG, "Bluetooth SCO audio is not available off call");
    return;
  }
  logBluetoothAdapterInfo(bluetoothAdapter);
  // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
  // Hands-Free) proxy object and install a listener.
  if (!getBluetoothProfileProxy(
          apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
    Log.e(TAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
    return;
  }
  // Register receivers for BluetoothHeadset change notifications.
  IntentFilter bluetoothHeadsetFilter = new IntentFilter();
  // Register receiver for change in connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
  // Register receiver for change in audio connection state of the Headset profile.
  bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
  registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
  Log.d(TAG, "HEADSET profile state: "
          + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
  Log.d(TAG, "Bluetooth proxy for headset profile has started");
  bluetoothState = State.HEADSET_UNAVAILABLE;
  Log.d(TAG, "start done: BT state=" + bluetoothState);
}
 
Example 25
/**
 * Activates components required to detect Bluetooth devices and to enable
 * BT SCO (audio is routed via BT SCO) for the headset profile. The end
 * state will be HEADSET_UNAVAILABLE but a state machine has started which
 * will start a state change sequence where the final outcome depends on
 * if/when the BT headset is enabled.
 * Example of state change sequence when start() is called while BT device
 * is connected and enabled:
 * UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
 * SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
 * Note that the AppRTCAudioManager is also involved in driving this state
 * change.
 */
public void start() {
    ThreadUtils.checkIsOnMainThread();
    Log.d(Config.LOGTAG, "start");
    if (!hasPermission(apprtcContext, android.Manifest.permission.BLUETOOTH)) {
        Log.w(Config.LOGTAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
        return;
    }
    if (bluetoothState != State.UNINITIALIZED) {
        Log.w(Config.LOGTAG, "Invalid BT state");
        return;
    }
    bluetoothHeadset = null;
    bluetoothDevice = null;
    scoConnectionAttempts = 0;
    // Get a handle to the default local Bluetooth adapter.
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Log.w(Config.LOGTAG, "Device does not support Bluetooth");
        return;
    }
    // Ensure that the device supports use of BT SCO audio for off call use cases.
    if (!audioManager.isBluetoothScoAvailableOffCall()) {
        Log.e(Config.LOGTAG, "Bluetooth SCO audio is not available off call");
        return;
    }
    logBluetoothAdapterInfo(bluetoothAdapter);
    // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
    // Hands-Free) proxy object and install a listener.
    if (!getBluetoothProfileProxy(
            apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
        Log.e(Config.LOGTAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
        return;
    }
    // Register receivers for BluetoothHeadset change notifications.
    IntentFilter bluetoothHeadsetFilter = new IntentFilter();
    // Register receiver for change in connection state of the Headset profile.
    bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    // Register receiver for change in audio connection state of the Headset profile.
    bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
    registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
    Log.d(Config.LOGTAG, "HEADSET profile state: "
            + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
    Log.d(Config.LOGTAG, "Bluetooth proxy for headset profile has started");
    bluetoothState = State.HEADSET_UNAVAILABLE;
    Log.d(Config.LOGTAG, "start done: BT state=" + bluetoothState);
}
 
Example 26
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	try {
		AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)!=null) {
			int outFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
			TgVoip.setBufferSize(outFramesPerBuffer);
		} else {
			TgVoip.setBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
		}

		cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
		cpuWakelock.acquire();

		btAdapter=am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		if(!USE_CONNECTION_SERVICE){
			filter.addAction(ACTION_HEADSET_PLUG);
			if(btAdapter!=null){
				filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
				filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
			}
			filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		}
		registerReceiver(receiver, filter);

		soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
		spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
		spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
		spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
		spEndId = soundPool.load(this, R.raw.voip_end, 1);
		spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

		am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

		if(!USE_CONNECTION_SERVICE && btAdapter!=null && btAdapter.isEnabled()){
			int headsetState=btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
			updateBluetoothHeadsetState(headsetState==BluetoothProfile.STATE_CONNECTED);
			//if(headsetState==BluetoothProfile.STATE_CONNECTED)
			//	am.setBluetoothScoOn(true);
			for (StateListener l : stateListeners)
				l.onAudioSettingsChanged();
		}
	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 27
/**
 * Activates components required to detect Bluetooth devices and to enable
 * BT SCO (audio is routed via BT SCO) for the headset profile. The end
 * state will be HEADSET_UNAVAILABLE but a state machine has started which
 * will start a state change sequence where the final outcome depends on
 * if/when the BT headset is enabled.
 * Example of state change sequence when start() is called while BT device
 * is connected and enabled:
 * UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
 * SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
 * Note that the AppRTCAudioManager is also involved in driving this state
 * change.
 */
public void start() {
    ThreadUtils.checkIsOnMainThread();
    Log.d(Config.LOGTAG, "start");
    if (!hasPermission(apprtcContext, android.Manifest.permission.BLUETOOTH)) {
        Log.w(Config.LOGTAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
        return;
    }
    if (bluetoothState != State.UNINITIALIZED) {
        Log.w(Config.LOGTAG, "Invalid BT state");
        return;
    }
    bluetoothHeadset = null;
    bluetoothDevice = null;
    scoConnectionAttempts = 0;
    // Get a handle to the default local Bluetooth adapter.
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Log.w(Config.LOGTAG, "Device does not support Bluetooth");
        return;
    }
    // Ensure that the device supports use of BT SCO audio for off call use cases.
    if (!audioManager.isBluetoothScoAvailableOffCall()) {
        Log.e(Config.LOGTAG, "Bluetooth SCO audio is not available off call");
        return;
    }
    logBluetoothAdapterInfo(bluetoothAdapter);
    // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
    // Hands-Free) proxy object and install a listener.
    if (!getBluetoothProfileProxy(
            apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
        Log.e(Config.LOGTAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
        return;
    }
    // Register receivers for BluetoothHeadset change notifications.
    IntentFilter bluetoothHeadsetFilter = new IntentFilter();
    // Register receiver for change in connection state of the Headset profile.
    bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    // Register receiver for change in audio connection state of the Headset profile.
    bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
    registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
    Log.d(Config.LOGTAG, "HEADSET profile state: "
            + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
    Log.d(Config.LOGTAG, "Bluetooth proxy for headset profile has started");
    bluetoothState = State.HEADSET_UNAVAILABLE;
    Log.d(Config.LOGTAG, "start done: BT state=" + bluetoothState);
}
 
Example 28
Source Project: Telegram   Source File: VoIPBaseService.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	try {
		AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)!=null) {
			int outFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
			TgVoip.setBufferSize(outFramesPerBuffer);
		} else {
			TgVoip.setBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
		}

		cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
		cpuWakelock.acquire();

		btAdapter=am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		if(!USE_CONNECTION_SERVICE){
			filter.addAction(ACTION_HEADSET_PLUG);
			if(btAdapter!=null){
				filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
				filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
			}
			filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		}
		registerReceiver(receiver, filter);

		soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
		spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
		spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
		spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
		spEndId = soundPool.load(this, R.raw.voip_end, 1);
		spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

		am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

		if(!USE_CONNECTION_SERVICE && btAdapter!=null && btAdapter.isEnabled()){
			int headsetState=btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
			updateBluetoothHeadsetState(headsetState==BluetoothProfile.STATE_CONNECTED);
			//if(headsetState==BluetoothProfile.STATE_CONNECTED)
			//	am.setBluetoothScoOn(true);
			for (StateListener l : stateListeners)
				l.onAudioSettingsChanged();
		}
	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 29
Source Project: AssistantBySDK   Source File: SystemVoiceMediator.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 获取蓝牙耳机对象
 **/
BluetoothHeadset getBluetoothHeadset();