android 蓝牙耳机播放音乐 代码
时间: 2023-07-30 17:10:36 浏览: 88
android蓝牙代码
5星 · 资源好评率100%
以下是在Android上连接蓝牙耳机并播放音乐的示例代码:
```java
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
return;
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
mediaPlayer = MediaPlayer.create(this, R.raw.music);
Button playButton = findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (bluetoothDevice == null) {
Toast.makeText(MainActivity.this, "No Bluetooth device connected", Toast.LENGTH_SHORT).show();
return;
}
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
});
Button stopButton = findViewById(R.id.stopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaPlayer.seekTo(0);
}
}
});
Button connectButton = findViewById(R.id.connectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equals("Bluetooth Headset")) {
bluetoothDevice = device;
Toast.makeText(MainActivity.this, "Bluetooth device connected", Toast.LENGTH_SHORT).show();
}
}
}
};
```
在这个示例中,我们首先检查设备是否支持蓝牙,如果不支持蓝牙,则显示一条消息。然后,我们检查蓝牙是否已启用,如果未启用,则请求用户启用蓝牙。接下来,我们设置一个广播接收器来监听蓝牙设备的发现事件。当用户点击“连接”按钮时,我们开始搜索蓝牙设备。如果找到一个名为“Bluetooth Headset”的设备,则保存该设备以供播放音乐时使用。当用户点击“播放”按钮时,我们检查是否已连接蓝牙设备,如果已连接,则开始播放音乐。当用户点击“停止”按钮时,我们暂停音乐并将其重新设置到起始位置。
阅读全文