首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限

<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permissionandroid:name="android.permission.BLUETOOTH" />

 

然后,看下api,Android所有关于蓝牙开发的类都在android.bluetooth包下,只有8个类,而我们需要用到了就只有几个而已:

1.BluetoothAdapter 顾名思义,蓝牙适配器,直到我们建立bluetoothSocket连接之前,都要不断操作它

BluetoothAdapter中的动作常量

ACTION_DISCOVERY_FINISHED 已完成蓝牙搜索 ACTION_DISCOVERY_STARTED 已经开始搜索蓝牙设备 ACTION_LOCAL_NAME_CHANGED 更改蓝牙的名字 ACTION_REQUEST_DISCOVERABLE 请求能够被搜索 ACTION_REQUEST_ENABLE 请求启动蓝牙 ACTION_SCAN_MODE_CHANGED 扫描模式已经改变 ACTION_STATE_CHANGED 状态已改变

 

BluetoothAdapter里的方法很多,常用的有以下几个:

cancelDiscovery() 根据字面意思,是取消发现,也就是说当我们正在搜索设备的时候调用这个方法将不再继续搜索

disable()关闭蓝牙

enable()打开蓝牙,这个方法打开蓝牙不会弹出提示,更多的时候我们需要问下用户是否打开,一下这两行代码同样是打开蓝牙,不过会提示用户:

请求开启蓝牙

Intemtenabler=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(Intemtenabler,reCode);//同startActivity(enabler);

 

请求能够被搜索

Intemtenabler=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(Intemtenabler,reCode);//同startActivity(enabler);

 

getAddress()获取本地蓝牙地址

getDefaultAdapter()获取默认BluetoothAdapter,实际上,也只有这一种方法获取BluetoothAdapter

getName()获取本地蓝牙名称

getRemoteDevice(String address)根据蓝牙地址获取远程蓝牙设备

getState()获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)

isDiscovering()判断当前是否正在查找设备,是返回true

isEnabled()判断蓝牙是否打开,已打开返回true,否则,返回false

listenUsingRfcommWithServiceRecord(String name,UUID uuid)根据名称,UUID创建并返回

BluetoothServerSocket,这是创建BluetoothSocket服务器端的第一步

startDiscovery()开始搜索,这是搜索的第一步

BluetoothAdapter里的方法很多,常用的有以下几个:

cancelDiscovery() 根据字面意思,是取消发现,也就是说当我们正在搜索设备的时候调用这个方法将不再继续搜索

disable()关闭蓝牙

enable()打开蓝牙,这个方法打开蓝牙不会弹出提示,更多的时候我们需要问下用户是否打开,一下这两行代码同样是打开蓝牙,不过会提示用户:

2.BluetoothDevice看名字就知道,这个类描述了一个蓝牙设备

createRfcommSocketToServiceRecord(UUIDuuid)根据UUID创建并返回一个BluetoothSocket

这个方法也是我们获取BluetoothDevice的目的——创建BluetoothSocket

这个类其他的方法,如getAddress(),getName(),同BluetoothAdapter

3.BluetoothServerSocket如果去除了Bluetooth相信大家一定再熟悉不过了,既然是Socket,方法就应该都差不多,这个类一种只有三个方法

两个重载的accept(),accept(inttimeout)两者的区别在于后面的方法指定了过时时间,需要注意的是,执行这两个方法的时候,直到接收到了客户端的请求(或是过期之后),都会阻塞线程,应该放在新线程里运行!

还有一点需要注意的是,这两个方法都返回一个BluetoothSocket,最后的连接也是服务器端与客户端的两个BluetoothSocket的连接

close()这个就不用说了吧,翻译一下——关闭!

4.BluetoothSocket,跟BluetoothServerSocket相对,是客户端

一共5个方法,不出意外,都会用到

close(),关闭

connect()连接

getInptuStream()获取输入流

getOutputStream()获取输出流

getRemoteDevice()获取远程设备,这里指的是获取bluetoothSocket指定连接的那个远程蓝牙设备

5:搜索蓝牙设备

public class DiscoveryActivity  extends ListActivity{private Handler _handler = new Handler();/* 取得默认的蓝牙适配器 */private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();/* 用来存储搜索到的蓝牙设备 */private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();/* 是否完成搜索 */private volatile boolean _discoveryFinished;private Runnable _discoveryWorkder = new Runnable() {public void run() {/* 开始搜索 */_bluetooth.startDiscovery();for (;;) {if (_discoveryFinished) {break;}try {Thread.sleep(100);} catch (InterruptedException e){}}}};/** * 接收器 * 当搜索蓝牙设备完成时调用 */private BroadcastReceiver _foundReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {/* 从intent中取得搜索结果数据 */BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);/* 将结果添加到列表中 */_devices.add(device);/* 显示列表 */showDevices();}};private BroadcastReceiver _discoveryReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {/* 卸载注册的接收器 */unregisterReceiver(_foundReceiver);unregisterReceiver(this);_discoveryFinished = true;}};protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);setContentView(R.layout.discovery);/* 如果蓝牙适配器没有打开,则结果 */if (!_bluetooth.isEnabled()){finish();return;}/* 注册接收器 */IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(_discoveryReceiver, discoveryFilter);IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(_foundReceiver, foundFilter);/* 显示一个对话框,正在搜索蓝牙设备 */SamplesUtils.indeterminate(DiscoveryActivity.this, _handler, "Scanning...", _discoveryWorkder, new OnDismissListener() {public void onDismiss(DialogInterface dialog){for (; _bluetooth.isDiscovering();){_bluetooth.cancelDiscovery();}_discoveryFinished = true;}}, true);}/* 显示列表 */protected void showDevices(){List<String> list = new ArrayList<String>();for (int i = 0, size = _devices.size(); i < size; ++i){StringBuilder b = new StringBuilder();BluetoothDevice d = _devices.get(i);b.append(d.getAddress());b.append('\n');b.append(d.getName());String s = b.toString();list.add(s);}final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);_handler.post(new Runnable() {public void run(){setListAdapter(adapter);}});}protected void onListItemClick(ListView l, View v, int position, long id){Intent result = new Intent();result.putExtra(BluetoothDevice.EXTRA_DEVICE, _devices.get(position));setResult(RESULT_OK, result);finish();}}

更多相关文章

  1. ueventd.rc 处理硬件设备权限和android init 对其解析
  2. Android中的onCreateOptionsMenu()方法和onOptionsItemSelected()方
  3. 关于androidSDK更新缓慢的解决方法(以W7为例)
  4. 执行Android JUnit测试出现java.net.SocketException: Permissio
  5. [android]notifyDataSetChanged方法
  6. Android后台发送短信方法
  7. Android 检查应用是否安装、唤起的方法
  8. Could not find com.android.tools.build:aapt2:3.3.2-5309881.
  9. Android实现计时与倒计时的几种方法

随机推荐

  1. 卷二 Dalvik与Android源码分析 第二章 进
  2. android studio 2.3.1 NDK开发入门实例
  3. Python String 的replace()与List的remov
  4. 通过抢红包插件学习Accessibility Servic
  5. Android(安卓)线程消息循环机制
  6. android DHCP流程
  7. Android运行模式 未验证
  8. Android(安卓)Studio打包,jar,arr,apk
  9. android textview在code(代码)中设置图片
  10. android - Actionbar 上的 MenuItem 的 使