Android 扫描附近的蓝牙设备并连接蓝牙音响的示例

转载:http://www.jb51.net/article/123248.htm

写了一个可以扫描附近蓝牙设备的小Demo,可以查看蓝牙设备的设备名和Mac地址

代码量不多,很容易看懂

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

/**

 * 作者:叶应是叶

 * 时间:2017/9/8 20:13

 * 描述:

 */

public class ScanDeviceActivity extends AppCompatActivity {

 

 private LoadingDialog loadingDialog;

 

 private DeviceAdapter deviceAdapter;

 

 private BluetoothAdapter bluetoothAdapter;

 

 private Handler handler = newHandler();

 

 privateBroadcastReceiver discoveryReceiver = newBroadcastReceiver() {

  @Override

  publicvoidonReceive(Context context, Intent intent) {

   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:

     BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

     deviceAdapter.addDevice(bluetoothDevice);

     deviceAdapter.notifyDataSetChanged();

     break;

   }

  }

 };

 

 

 @Override

 protectedvoidonCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_scan_device);

  BluetoothManager bluetoothManager = (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() {

  ListView lv_deviceList = (ListView) findViewById(R.id.lv_deviceList);

  deviceAdapter = newDeviceAdapter(this);

  lv_deviceList.setAdapter(deviceAdapter);

 }

 

 privatevoidregisterDiscoveryReceiver() {

  IntentFilter intentFilter = 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(String message) {

  if(loadingDialog == null) {

   loadingDialog = newLoadingDialog(this);

  }

  loadingDialog.show(message,true,false);

 }

 

 privatevoidhideLoadingDialog() {

  if(loadingDialog != null) {

   loadingDialog.dismiss();

  }

 }

 

}

 

此外,还可以通过利用反射来调用系统API,从而与支持蓝牙A2DP协议的蓝牙音响连接上,不过因为我只有一部不算严格意义上的蓝牙音响来做测试,所以这个功能并不确定是否适用于大多数蓝牙设备

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

/**

 * 作者:叶应是叶

 * 时间:2017/9/8 20:02

 * 描述:

 */

publicclassConnectA2dpActivity extendsAppCompatActivity {

 

 privateDeviceAdapter deviceAdapter;

 

 privateBluetoothAdapter bluetoothAdapter;

 

 privateHandler handler = newHandler();

 

 privateBluetoothA2dp bluetoothA2dp;

 

 privateLoadingDialog loadingDialog;

 

 privatefinalString TAG = "ConnectA2dpActivity";

 

 privateBroadcastReceiver a2dpReceiver = newBroadcastReceiver() {

 

  @Override

  publicvoidonReceive(Context context, Intent intent) {

   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;

   }

  }

 };

 

 privateBroadcastReceiver discoveryReceiver = newBroadcastReceiver() {

  @Override

  publicvoidonReceive(Context context, Intent intent) {

   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:

     BluetoothDevice bluetoothDevice = 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.ServiceListener profileServiceListener = newBluetoothProfile.ServiceListener() {

 

  @Override

  publicvoidonServiceDisconnected(intprofile) {

   if(profile == BluetoothProfile.A2DP) {

    Toast.makeText(ConnectA2dpActivity.this,"onServiceDisconnected", Toast.LENGTH_SHORT).show();

    bluetoothA2dp = null;

   }

  }

 

  @Override

  publicvoidonServiceConnected(intprofile,finalBluetoothProfile proxy) {

   if(profile == BluetoothProfile.A2DP) {

    Toast.makeText(ConnectA2dpActivity.this,"onServiceConnected", Toast.LENGTH_SHORT).show();

    bluetoothA2dp = (BluetoothA2dp) proxy;

   }

  }

 };

 

 privateAdapterView.OnItemClickListener itemClickListener = newAdapterView.OnItemClickListener() {

  @Override

  publicvoidonItemClick(AdapterView<?> parent, View view, intposition,longid) {

   BluetoothDevice device = deviceAdapter.getDevice(position);

   if(device.getBondState() == BluetoothDevice.BOND_BONDED) {

    Toast.makeText(ConnectA2dpActivity.this,"已连接该设备", Toast.LENGTH_SHORT).show();

    return;

   }

   showLoadingDialog("正在连接");

   connectA2dp(device);

  }

 };

 

 

 @Override

 protectedvoidonCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_connect_a2dp);

  BluetoothManager bluetoothManager = (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() {

  ListView lv_deviceList = (ListView) findViewById(R.id.lv_deviceList);

  deviceAdapter = newDeviceAdapter(this);

  lv_deviceList.setAdapter(deviceAdapter);

  lv_deviceList.setOnItemClickListener(itemClickListener);

 }

 

 privatevoidregisterDiscoveryReceiver() {

  IntentFilter intentFilter = 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() {

  IntentFilter intentFilter = 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(BluetoothDevice device, intpriority) {

  try{

   Method connectMethod = BluetoothA2dp.class.getMethod("setPriority", BluetoothDevice.class,int.class);

   connectMethod.invoke(bluetoothA2dp, device, priority);

  }catch(Exception e) {

   e.printStackTrace();

  }

 }

 

 privatevoidconnectA2dp(BluetoothDevice bluetoothDevice) {

  if(bluetoothA2dp == null|| bluetoothDevice == null) {

   return;

  }

  setPriority(bluetoothDevice,100);

  try{

   Method connectMethod = BluetoothA2dp.class.getMethod("connect", BluetoothDevice.class);

   connectMethod.invoke(bluetoothA2dp, bluetoothDevice);

  }catch(Exception e) {

   e.printStackTrace();

  }

 }

 

 privatevoidshowLoadingDialog(String message) {

  if(loadingDialog == null) {

   loadingDialog = newLoadingDialog(this);

  }

  loadingDialog.show(message,true,false);

 }

 

 privatevoidhideLoadingDialog() {

  if(loadingDialog != null) {

   loadingDialog.dismiss();

  }

 }

 

}

这里给出源代码供大家参考:BluetoothDemo 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

原文链接:http://www.jianshu.com/p/e2a24e871575?utm_source=tuicool&utm_medium=referral

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值