android 连接蓝牙耳机 播放音乐,Android连接蓝牙耳机播放音乐

这个博客详细介绍了如何在Android设备上实现连接蓝牙耳机并播放音乐的步骤,包括初始化参数、蓝牙设备搜索、配对连接、播放音乐以及管理蓝牙连接状态的监听。通过注册广播接收器监听蓝牙设备的状态变化,确保在蓝牙耳机连接成功后开始音乐播放,并在播放完成后断开连接。
摘要由CSDN通过智能技术生成

参考:

具体实现:

private static final String TAG = "BluetoothA2DPTest";

private BroadcastReceiver mBroadcastReceiver;

private BluetoothA2dp mBluetoothA2dp;

private BluetoothAdapter mBluetoothAdapter;

private String DEVICE_NAME = "KUWO_K1";

private BluetoothDevice mBluetoothDevice;

private MediaPlayer mMediaPlayer;

private void initParameters(){

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if(mBluetoothAdapter == null){

Log.e(TAG,"have no bluetooth adapter.");

return;

}

if(!mBluetoothAdapter.isEnabled()){

mBluetoothAdapter.enable();

}else{

//开始搜索附近蓝牙

startDiscovery();

//绑定BluetoothA2DP,获得service

getBluetoothA2DP();

}

//监听广播

mBroadcastReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

BluetoothDevice device;

switch (intent.getAction()) {

case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:

//

switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {

case BluetoothA2dp.STATE_CONNECTING:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Log.i(TAG, "device: " + device.getName() +" connecting");

break;

case BluetoothA2dp.STATE_CONNECTED:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Log.i(TAG, "device: " + device.getName() +" connected");

//连接成功,开始播放

startPlay();

break;

case BluetoothA2dp.STATE_DISCONNECTING:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Log.i(TAG, "device: " + device.getName() +" disconnecting");

break;

case BluetoothA2dp.STATE_DISCONNECTED:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Log.i(TAG, "device: " + device.getName() +" disconnected");

// setResultPASS();

break;

default:

break;

}

//

break;

case BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:

//

int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1);

switch (state) {

case BluetoothA2dp.STATE_PLAYING:

Log.i(TAG, "state: playing.");

break;

case BluetoothA2dp.STATE_NOT_PLAYING:

Log.i(TAG, "state: not playing");

break;

default:

Log.i(TAG, "state: unkown

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值