android.bluetooth.BluetoothA2dp Java Examples

The following examples show how to use android.bluetooth.BluetoothA2dp. 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
Source File: BluetoothA2dpSnippet.java    From mobly-bundled-snippets with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
@RpcMinSdk(Build.VERSION_CODES.KITKAT)
@Rpc(
        description =
                "Connects to a paired or discovered device with A2DP profile."
                        + "If a device has been discovered but not paired, this will pair it.")
public void btA2dpConnect(String deviceAddress) throws Throwable {
    BluetoothDevice device = BluetoothAdapterSnippet.getKnownDeviceByAddress(deviceAddress);
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    mContext.registerReceiver(new PairingBroadcastReceiver(mContext), filter);
    Utils.invokeByReflection(sA2dpProfile, "connect", device);
    if (!Utils.waitUntil(
            () -> sA2dpProfile.getConnectionState(device) == BluetoothA2dp.STATE_CONNECTED,
            120)) {
        throw new BluetoothA2dpSnippetException(
                "Failed to connect to device "
                        + device.getName()
                        + "|"
                        + device.getAddress()
                        + " with A2DP profile within 2min.");
    }
}
 
Example #2
Source File: BluetoothActivity.java    From bluetooth-a2dp with Apache License 2.0 5 votes vote down vote up
/**
 * Wrapper around some reflection code to get the hidden 'connect()' method
 * @return the connect(BluetoothDevice) method, or null if it could not be found
 */
private Method getConnectMethod () {
    try {
        return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
    } catch (NoSuchMethodException ex) {
        Log.e(TAG, "Unable to find connect(BluetoothDevice) method in BluetoothA2dp proxy.");
        return null;
    }
}
 
Example #3
Source File: MediaRouterService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(BluetoothA2dp.ACTION_ACTIVE_DEVICE_CHANGED)) {
        BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        synchronized (mLock) {
            mActiveBluetoothDevice = btDevice;
            mGlobalBluetoothA2dpOn = btDevice != null;
        }
    }
}
 
Example #4
Source File: BluetoothReceiver.java    From ClassicBluetooth with 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 #5
Source File: AssistantService.java    From AssistantBySDK with 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 #6
Source File: MainActivity.java    From BlueToothEatPhone with Apache License 2.0 5 votes vote down vote up
@Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            try {
                if (profile == BluetoothProfile.HEADSET) {
//                    bh = (BluetoothHeadset) proxy;
//                    if (bh.getConnectionState(mTouchObject.bluetoothDevice) != BluetoothProfile.STATE_CONNECTED){
//                        bh.getClass()
//                                .getMethod("connect", BluetoothDevice.class)
//                                .invoke(bh, mTouchObject.bluetoothDevice);
//                    }

                } else if (profile == BluetoothProfile.A2DP) {
                    /**使用A2DP的协议连接蓝牙设备(使用了反射技术调用连接的方法)*/
                    a2dp = (BluetoothA2dp) proxy;
                    if (a2dp.getConnectionState(currentBluetoothDevice) != BluetoothProfile.STATE_CONNECTED) {
                        a2dp.getClass()
                                .getMethod("connect", BluetoothDevice.class)
                                .invoke(a2dp, currentBluetoothDevice);
                        Toast.makeText(MainActivity.this,"请播放音乐",Toast.LENGTH_SHORT).show();
                        getBondedDevices();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
Example #7
Source File: BleManager.java    From EasyBluetoothFrame with Apache License 2.0 5 votes vote down vote up
private void registerReceiver() {
        if (resultListener != null)
            mReceiver.setScanResultListener(resultListener);
//        if(pinResultListener!=null)
//            mReceiver.setPinResultListener(pinResultListener);
//        if(cancelPinResultListener!=null)
//            mReceiver.setCancelPinResultListener(cancelPinResultListener);
        if (clientConnectResultListener != null)
            mReceiver.setClientConnectResultListener(clientConnectResultListener);
        if (serverConnectResultListener != null)
            mReceiver.setServerConnectResultListener(serverConnectResultListener);
        if (!isRegister) {
            isRegister = true;
            // Register the BroadcastReceiver
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
            filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
            filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
            filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
            //<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            //    <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
            //    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            application.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        }
    }
 
Example #8
Source File: BluetoothA2dpSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@Rpc(description = "Disconnects a device from A2DP profile.")
public void btA2dpDisconnect(String deviceAddress) throws Throwable {
    BluetoothDevice device = getConnectedBluetoothDevice(deviceAddress);
    Utils.invokeByReflection(sA2dpProfile, "disconnect", device);
    if (!Utils.waitUntil(
            () -> sA2dpProfile.getConnectionState(device) == BluetoothA2dp.STATE_DISCONNECTED,
            120)) {
        throw new BluetoothA2dpSnippetException(
                "Failed to disconnect device "
                        + device.getName()
                        + "|"
                        + device.getAddress()
                        + " from A2DP profile within 2min.");
    }
}
 
Example #9
Source File: BluetoothA2dpSnippet.java    From mobly-bundled-snippets with Apache License 2.0 4 votes vote down vote up
public void onServiceConnected(int var1, BluetoothProfile profile) {
    sA2dpProfile = (BluetoothA2dp) profile;
    sIsA2dpProfileReady = true;
}
 
Example #10
Source File: BluetoothA2DPRequester.java    From bluetooth-a2dp with Apache License 2.0 4 votes vote down vote up
@Override
public void onServiceConnected(int i, BluetoothProfile bluetoothProfile) {
    if (mCallback != null) {
        mCallback.onA2DPProxyReceived((BluetoothA2dp) bluetoothProfile);
    }
}
 
Example #11
Source File: DefaultBluetoothHandler.java    From SimpleBluetoothLibrary with Apache License 2.0 4 votes vote down vote up
@Override
public void handleMessage(Message message) {
    switch (message.what) {
        case MESSAGE_READ:
            byte[] readBuf = (byte[]) message.obj;
            //get how many bytes were actually read.
            int datalength = message.arg1;
            String readMessage = new String(readBuf, 0, datalength);
            if(readBuf.length > 0) {
                if(mListener != null)
                    mListener.onBluetoothDataReceived(readBuf, readMessage);
            }
            break;
        case MESSAGE_WAIT_FOR_CONNECTION:
            if(dialog != null) {
                dialog.setTitle("");
                dialog.setMessage("Waiting...");
                dialog.show();
            }
            break;
        case MESSAGE_CONNECTION_MADE:
            if(dialog != null) {
                if(dialog.isShowing()) {
                    dialog.dismiss();
                    if(shouldShowSnackbars && mActivity != null) {
                        Snackbar.make(mActivity.findViewById(android.R.id.content), "Device connected.",
                                Snackbar.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        case MESSAGE_A2DP_PROXY_RECEIVED:
            BluetoothA2dp device = (BluetoothA2dp) message.obj;
            if(device != null && mListener != null) {
                mListener.onBluetoothA2DPRequested(device);
            }
            break;
        default:
            break;
    }
}
 
Example #12
Source File: BluetoothUtility.java    From SimpleBluetoothLibrary with Apache License 2.0 4 votes vote down vote up
@Override
public void onServiceConnected(int i, BluetoothProfile bluetoothProfile) {
    bluetoothHandler
            .obtainMessage(BluetoothHandler.MESSAGE_A2DP_PROXY_RECEIVED,(BluetoothA2dp) bluetoothProfile)
            .sendToTarget();
}
 
Example #13
Source File: VoiceMediator.java    From AssistantBySDK with Apache License 2.0 4 votes vote down vote up
@Override
public BluetoothA2dp getBluetoothA2dp() {
    return bluetoothA2dp;
}
 
Example #14
Source File: VoiceMediator.java    From AssistantBySDK with Apache License 2.0 4 votes vote down vote up
public void setBluetoothA2dp(BluetoothA2dp bluetoothA2dp) {
    this.bluetoothA2dp = bluetoothA2dp;
}
 
Example #15
Source File: BluetoothReceiver.java    From ClassicBluetooth with 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 #16
Source File: MediaRouterService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public MediaRouterService(Context context) {
    mContext = context;
    Watchdog.getInstance().addMonitor(this);

    mAudioService = IAudioService.Stub.asInterface(
            ServiceManager.getService(Context.AUDIO_SERVICE));
    mAudioPlayerStateMonitor = AudioPlayerStateMonitor.getInstance();
    mAudioPlayerStateMonitor.registerListener(
            new AudioPlayerStateMonitor.OnAudioPlayerActiveStateChangedListener() {
        static final long WAIT_MS = 500;
        final Runnable mRestoreBluetoothA2dpRunnable = new Runnable() {
            @Override
            public void run() {
                restoreBluetoothA2dp();
            }
        };

        @Override
        public void onAudioPlayerActiveStateChanged(
                @NonNull AudioPlaybackConfiguration config, boolean isRemoved) {
            final boolean active = !isRemoved && config.isActive();
            final int pii = config.getPlayerInterfaceId();
            final int uid = config.getClientUid();

            final int idx = mActivePlayerMinPriorityQueue.indexOf(pii);
            // Keep the latest active player and its uid at the end of the queue.
            if (idx >= 0) {
                mActivePlayerMinPriorityQueue.remove(idx);
                mActivePlayerUidMinPriorityQueue.remove(idx);
            }

            int restoreUid = -1;
            if (active) {
                mActivePlayerMinPriorityQueue.add(config.getPlayerInterfaceId());
                mActivePlayerUidMinPriorityQueue.add(uid);
                restoreUid = uid;
            } else if (mActivePlayerUidMinPriorityQueue.size() > 0) {
                restoreUid = mActivePlayerUidMinPriorityQueue.get(
                        mActivePlayerUidMinPriorityQueue.size() - 1);
            }

            mHandler.removeCallbacks(mRestoreBluetoothA2dpRunnable);
            if (restoreUid >= 0) {
                restoreRoute(restoreUid);
                if (DEBUG) {
                    Slog.d(TAG, "onAudioPlayerActiveStateChanged: " + "uid=" + uid
                            + ", active=" + active + ", restoreUid=" + restoreUid);
                }
            } else {
                mHandler.postDelayed(mRestoreBluetoothA2dpRunnable, WAIT_MS);
                if (DEBUG) {
                    Slog.d(TAG, "onAudioPlayerActiveStateChanged: " + "uid=" + uid
                            + ", active=" + active + ", delaying");
                }
            }
        }
    }, mHandler);
    mAudioPlayerStateMonitor.registerSelfIntoAudioServiceIfNeeded(mAudioService);

    AudioRoutesInfo audioRoutes = null;
    try {
        audioRoutes = mAudioService.startWatchingRoutes(new IAudioRoutesObserver.Stub() {
            @Override
            public void dispatchAudioRoutesChanged(final AudioRoutesInfo newRoutes) {
                synchronized (mLock) {
                    if (newRoutes.mainType != mAudioRouteMainType) {
                        if ((newRoutes.mainType & (AudioRoutesInfo.MAIN_HEADSET
                                | AudioRoutesInfo.MAIN_HEADPHONES
                                | AudioRoutesInfo.MAIN_USB)) == 0) {
                            // headset was plugged out.
                            mGlobalBluetoothA2dpOn = (newRoutes.bluetoothName != null
                                    || mActiveBluetoothDevice != null);
                        } else {
                            // headset was plugged in.
                            mGlobalBluetoothA2dpOn = false;
                        }
                        mAudioRouteMainType = newRoutes.mainType;
                    }
                    // The new audio routes info could be delivered with several seconds delay.
                    // In order to avoid such delay, Bluetooth device info will be updated
                    // via MediaRouterServiceBroadcastReceiver.
                }
            }
        });
    } catch (RemoteException e) {
        Slog.w(TAG, "RemoteException in the audio service.");
    }

    IntentFilter intentFilter = new IntentFilter(BluetoothA2dp.ACTION_ACTIVE_DEVICE_CHANGED);
    context.registerReceiverAsUser(mReceiver, UserHandle.ALL, intentFilter, null, null);
}
 
Example #17
Source File: SystemVoiceMediator.java    From AssistantBySDK with Apache License 2.0 2 votes vote down vote up
/**
 * 获取可操控蓝牙设备对象
 **/
BluetoothA2dp getBluetoothA2dp();
 
Example #18
Source File: SimpleBluetoothListener.java    From SimpleBluetoothLibrary with Apache License 2.0 votes vote down vote up
/**
 * Called when a request is made to connect to an A2dp device.
 * @param bluetoothA2dp the a2dp device.
 */
public void onBluetoothA2DPRequested(BluetoothA2dp bluetoothA2dp) {

}
 
Example #19
Source File: BluetoothA2DPRequester.java    From bluetooth-a2dp with Apache License 2.0 votes vote down vote up
public void onA2DPProxyReceived (BluetoothA2dp proxy);