Android 扫描周围蓝牙设备
2013-10-28 22:40
423 查看
package com.zhoucj.bluetooth; import android.os.Bundle; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button bluetoothBtn; BluetoothAdapter adapter;//本地蓝牙适配器 //BluetoothDevice device;//远程蓝牙适配器 BluetoothReceiver bluetoothReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bluetoothBtn=(Button)findViewById(R.id.bluetooth); bluetoothBtn.setOnClickListener(listener); //创建一个IntentFilter对象,将action指定为 BluetoothDevices.ACTION_FOUND; IntentFilter intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND); bluetoothReceiver=new BluetoothReceiver(); //注册广播接收器 registerReceiver(bluetoothReceiver, intentFilter); //获取本地蓝牙适配器 adapter=BluetoothAdapter.getDefaultAdapter(); } //广播接收器 private class BluetoothReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action=intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)) { //获取周围蓝牙设备 BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.i("msg", device.getAddress()); } } } private OnClickListener listener=new OnClickListener() { @Override public void onClick(View arg0) { if(adapter!=null) { //开始扫描周围的蓝牙设备 //如果扫描到蓝牙设备,通过广播接收器发送广播 adapter.startDiscovery(); }else { Log.i("msg", "没有蓝牙设备"); } } }; @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); //卸载广播接收器 unregisterReceiver(bluetoothReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
最后加上
<uses-permission android:name="android.permission.BLUETOOTH"/>
代码中都有注释,
相关文章推荐
- Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
- Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
- Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备(转)
- Android蓝牙扫描周围设备和连接
- android-扫描周围蓝牙设备
- Android开发之蓝牙 --修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
- Android bluetooth介绍(三): 蓝牙扫描(scan)设备分析
- Android 蓝牙自动打开并扫描设备,以及获取对方蓝牙设备的种类
- ANDROID_MARS学习笔记_S03_002_设置可见性及扫描蓝牙设备
- Android 6.0 Kotlin 蓝牙BLE扫描(改为指定时间没有发现新设备后停止扫描)
- Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备
- Android 扫描附近的蓝牙设备并连接蓝牙音响的示例
- Android bluetooth介绍(三): 蓝牙扫描(scan)设备分析
- Android蓝牙扫描设备过程
- Android 扫描附近的蓝牙设备并连接蓝牙音响的示例
- Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备
- android 蓝牙通讯实现手机蓝牙的开启,并扫描附近可见的蓝牙设备
- Android bluetooth介绍(三): 蓝牙扫描(scan)设备分析
- Android 扫描蓝牙设备
- android开发之蓝牙初步 扫描已配对蓝牙、更改蓝牙可见性、搜索外部蓝牙设备