Android 扫描附近的蓝牙设备并连接蓝牙音响的示例
写了一个可以扫描附近蓝牙设备的小Demo,可以查看蓝牙设备的设备名和Mac地址
代码量不多,很容易看懂
/**
*作者:叶应是叶
*时间:2017/9/820:13
*描述:
*/
publicclassScanDeviceActivityextendsAppCompatActivity{
privateLoadingDialogloadingDialog;
privateDeviceAdapterdeviceAdapter;
privateBluetoothAdapterbluetoothAdapter;
privateHandlerhandler=newHandler();
privateBroadcastReceiverdiscoveryReceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
switch(intent.getAction()){
caseBluetoothAdapter.ACTION_DISCOVERY_STARTED:
showLoadingDialog("正在搜索附近的蓝牙设备");
break;
caseBluetoothAdapter.ACTION_DISCOVERY_FINISHED:
Toast.makeText(ScanDeviceActivity.this,"搜索结束",Toast.LENGTH_SHORT).show();
hideLoadingDialog();
break;
caseBluetoothDevice.ACTION_FOUND:
BluetoothDevicebluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceAdapter.addDevice(bluetoothDevice);
deviceAdapter.notifyDataSetChanged();
break;
}
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_device);
BluetoothManagerbluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter=bluetoothManager.getAdapter();
if(bluetoothAdapter==null){
Toast.makeText(this,"当前设备不支持蓝牙",Toast.LENGTH_SHORT).show();
finish();
}
initView();
registerDiscoveryReceiver();
startScan();
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
handler.removeCallbacksAndMessages(null);
unregisterReceiver(discoveryReceiver);
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
}
privatevoidinitView(){
ListViewlv_deviceList=(ListView)findViewById(R.id.lv_deviceList);
deviceAdapter=newDeviceAdapter(this);
lv_deviceList.setAdapter(deviceAdapter);
}
privatevoidregisterDiscoveryReceiver(){
IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(discoveryReceiver,intentFilter);
}
privatevoidstartScan(){
if(!bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.enable()){
handler.postDelayed(newRunnable(){
@Override
publicvoidrun(){
scanDevice();
}
},1500);
}else{
Toast.makeText(this,"请求蓝牙权限被拒绝,请授权",Toast.LENGTH_SHORT).show();
}
}else{
scanDevice();
}
}
privatevoidscanDevice(){
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
privatevoidshowLoadingDialog(Stringmessage){
if(loadingDialog==null){
loadingDialog=newLoadingDialog(this);
}
loadingDialog.show(message,true,false);
}
privatevoidhideLoadingDialog(){
if(loadingDialog!=null){
loadingDialog.dismiss();
}
}
}
此外,还可以通过利用反射来调用系统API,从而与支持蓝牙A2DP协议的蓝牙音响连接上,不过因为我只有一部不算严格意义上的蓝牙音响来做测试,所以这个功能并不确定是否适用于大多数蓝牙设备
/**
*作者:叶应是叶
*时间:2017/9/820:02
*描述:
*/
publicclassConnectA2dpActivityextendsAppCompatActivity{
privateDeviceAdapterdeviceAdapter;
privateBluetoothAdapterbluetoothAdapter;
privateHandlerhandler=newHandler();
privateBluetoothA2dpbluetoothA2dp;
privateLoadingDialogloadingDialog;
privatefinalStringTAG="ConnectA2dpActivity";
privateBroadcastReceivera2dpReceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
switch(intent.getAction()){
caseBluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
intconnectState=intent.getIntExtra(BluetoothA2dp.EXTRA_STATE,BluetoothA2dp.STATE_DISCONNECTED);
if(connectState==BluetoothA2dp.STATE_DISCONNECTED){
Toast.makeText(ConnectA2dpActivity.this,"已断开连接",Toast.LENGTH_SHORT).show();
}elseif(connectState==BluetoothA2dp.STATE_CONNECTED){
Toast.makeText(ConnectA2dpActivity.this,"已连接",Toast.LENGTH_SHORT).show();
}
break;
caseBluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:
intplayState=intent.getIntExtra(BluetoothA2dp.EXTRA_STATE,BluetoothA2dp.STATE_NOT_PLAYING);
if(playState==BluetoothA2dp.STATE_PLAYING){
Toast.makeText(ConnectA2dpActivity.this,"处于播放状态",Toast.LENGTH_SHORT).show();
}elseif(playState==BluetoothA2dp.STATE_NOT_PLAYING){
Toast.makeText(ConnectA2dpActivity.this,"未在播放",Toast.LENGTH_SHORT).show();
}
break;
}
}
};
privateBroadcastReceiverdiscoveryReceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
switch(intent.getAction()){
caseBluetoothAdapter.ACTION_DISCOVERY_STARTED:
showLoadingDialog("正在搜索蓝牙设备,搜索时间大约一分钟");
break;
caseBluetoothAdapter.ACTION_DISCOVERY_FINISHED:
Toast.makeText(ConnectA2dpActivity.this,"搜索蓝牙设备结束",Toast.LENGTH_SHORT).show();
hideLoadingDialog();
break;
caseBluetoothDevice.ACTION_FOUND:
BluetoothDevicebluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceAdapter.addDevice(bluetoothDevice);
deviceAdapter.notifyDataSetChanged();
break;
caseBluetoothDevice.ACTION_BOND_STATE_CHANGED:
intstatus=intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,BluetoothDevice.BOND_NONE);
if(status==BluetoothDevice.BOND_BONDED){
Toast.makeText(ConnectA2dpActivity.this,"已连接",Toast.LENGTH_SHORT).show();
}elseif(status==BluetoothDevice.BOND_NONE){
Toast.makeText(ConnectA2dpActivity.this,"未连接",Toast.LENGTH_SHORT).show();
}
hideLoadingDialog();
break;
}
}
};
privateBluetoothProfile.ServiceListenerprofileServiceListener=newBluetoothProfile.ServiceListener(){
@Override
publicvoidonServiceDisconnected(intprofile){
if(profile==BluetoothProfile.A2DP){
Toast.makeText(ConnectA2dpActivity.this,"onServiceDisconnected",Toast.LENGTH_SHORT).show();
bluetoothA2dp=null;
}
}
@Override
publicvoidonServiceConnected(intprofile,finalBluetoothProfileproxy){
if(profile==BluetoothProfile.A2DP){
Toast.makeText(ConnectA2dpActivity.this,"onServiceConnected",Toast.LENGTH_SHORT).show();
bluetoothA2dp=(BluetoothA2dp)proxy;
}
}
};
privateAdapterView.OnItemClickListeneritemClickListener=newAdapterView.OnItemClickListener(){
@Override
publicvoidonItemClick(AdapterView>parent,Viewview,intposition,longid){
BluetoothDevicedevice=deviceAdapter.getDevice(position);
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
Toast.makeText(ConnectA2dpActivity.this,"已连接该设备",Toast.LENGTH_SHORT).show();
return;
}
showLoadingDialog("正在连接");
connectA2dp(device);
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect_a2dp);
BluetoothManagerbluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter=bluetoothManager.getAdapter();
if(bluetoothAdapter==null||!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(ConnectA2dpActivity.this,"当前设备不支持蓝牙",Toast.LENGTH_SHORT).show();
finish();
}
bluetoothAdapter.getProfileProxy(this,profileServiceListener,BluetoothProfile.A2DP);
initView();
registerDiscoveryReceiver();
registerA2dpReceiver();
startScan();
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
handler.removeCallbacksAndMessages(null);
unregisterReceiver(a2dpReceiver);
unregisterReceiver(discoveryReceiver);
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
}
privatevoidinitView(){
ListViewlv_deviceList=(ListView)findViewById(R.id.lv_deviceList);
deviceAdapter=newDeviceAdapter(this);
lv_deviceList.setAdapter(deviceAdapter);
lv_deviceList.setOnItemClickListener(itemClickListener);
}
privatevoidregisterDiscoveryReceiver(){
IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(discoveryReceiver,intentFilter);
}
privatevoidregisterA2dpReceiver(){
IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
registerReceiver(a2dpReceiver,intentFilter);
}
privatevoidstartScan(){
if(!bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.enable()){
handler.postDelayed(newRunnable(){
@Override
publicvoidrun(){
scanDevice();
}
},1500);
}else{
Toast.makeText(ConnectA2dpActivity.this,"请求蓝牙权限被拒绝",Toast.LENGTH_SHORT).show();
}
}else{
scanDevice();
}
}
privatevoidscanDevice(){
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
publicvoidsetPriority(BluetoothDevicedevice,intpriority){
try{
MethodconnectMethod=BluetoothA2dp.class.getMethod("setPriority",BluetoothDevice.class,int.class);
connectMethod.invoke(bluetoothA2dp,device,priority);
}catch(Exceptione){
e.printStackTrace();
}
}
privatevoidconnectA2dp(BluetoothDevicebluetoothDevice){
if(bluetoothA2dp==null||bluetoothDevice==null){
return;
}
setPriority(bluetoothDevice,100);
try{
MethodconnectMethod=BluetoothA2dp.class.getMethod("connect",BluetoothDevice.class);
connectMethod.invoke(bluetoothA2dp,bluetoothDevice);
}catch(Exceptione){
e.printStackTrace();
}
}
privatevoidshowLoadingDialog(Stringmessage){
if(loadingDialog==null){
loadingDialog=newLoadingDialog(this);
}
loadingDialog.show(message,true,false);
}
privatevoidhideLoadingDialog(){
if(loadingDialog!=null){
loadingDialog.dismiss();
}
}
}
这里给出源代码供大家参考:BluetoothDemo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。