android开发笔记蓝牙

相关类:

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

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

                  cancelDiscovery() 取消搜索

                  disable()关闭蓝牙

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

		Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //打开蓝牙设备
		startActivity(intent);

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

                getName()获取本地蓝牙名称

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

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

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

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

                listenUsingRfcommWithServiceRecord(String name,UUID uuid)根据名称,UUID创建并返回BluetoothServerSocket,这是创建BluetoothSocket服务器端的第一步

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

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

               createRfcommSocketToServiceRecord(UUIDuuid)根据UUID创建并返回一个BluetoothSocket   这个方法也是我们获取BluetoothDevice的目的——创建BluetoothSocket

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

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

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

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

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

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

               close(),关闭

              connect()连接

              getInptuStream()获取输入流

              getOutputStream()获取输出流

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



权限:

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

<uses-permisson android:name="android.permission.BLUETOOTH_ADMIN" /> <!--操作蓝牙设备-->

广播

    BluetoothDevice.ACTION_FOUND//查找到一个蓝牙设备时广播
    BluetoothAdapter.ACTION_DISCOVERY_FINISHED//查找结束时 广播
    BluetoothDevice.ACTION_BOND_STATE_CHANGED //当蓝牙设备 匹配或者取消匹配时广播

1.打开蓝牙

				BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
				if(adapter!=null){
					if(!adapter.isEnabled()){ //查看蓝牙是否开启
						Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //打开蓝牙设备,这两句会出现提示框 enable()方法打开的蓝牙不会出现提示
						startActivity(intent);
					}
					Set<BluetoothDevice> devices=adapter.getBondedDevices();//得到所有配对的蓝牙视频器
					if(devices!=null&&devices.size()>0){
						Iterator<BluetoothDevice> ite=devices.iterator();
						for (BluetoothDevice bluetoothDevice : devices) {
							Toast.makeText(MainActivity.this, bluetoothDevice.getAddress()+"", Toast.LENGTH_SHORT).show();
						}
					}
					
				}
2 打开蓝牙的可见性,可以被其他蓝牙检测到

                                Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
				intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //设置可见时间 最高300秒 
				startActivity(intent);
3 扫描设备

	BluetoothAdapter.getDefaultAdapter().startDiscovery();//开始扫描 异步调用 查找到一个设备后发送一广播
	 //注册接收蓝牙广播的
        IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); //当接收到广播的
        registerReceiver(new BluetoothReceiver(), filter);		
        下面是广播接收器
        class BluetoothReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			Toast.makeText(MainActivity.this, device.getAddress()+"", Toast.LENGTH_SHORT).show();
		}		
	}  

4 匹配设配(利用反射机制)

	 Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
	 Boolean a = (Boolean) createBondMethod.invoke(device1
5连接(手头没俩手机.网上百度的..明天去搞个有错再修正,先记录下来)

方法1:使用反射

                                Method m = null;
				try {
					m = device.getClass().getMethod("createRfcommSocket",
							new Class[] { int.class });
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
				try {
					btSocket = (BluetoothSocket) m.invoke(device, 1);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				try {
					btSocket.connect();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
6 发送文件

/*
* 发送一指定的文件到其它蓝牙设备
*/
ContentValues cv = new ContentValues();
cv.put("uri", FilePath);
cv.put("destination", address);
cv.put("direction", 0);
Long ts = System.currentTimeMillis();
cv.put("timestamp", ts);
getContentResolver().insert(Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
btSocket.close();
/*
* 下面一段是通过intent的方式发送文件
* 与上面一段的不同在于,该方式会打开一个数据分享方式列表,如蓝牙,短信,Email 等
* 选择蓝牙方式后也是可以发送到其它蓝牙设备的
* 只不过偶尔也会抛出一个ioException异常,所以健壮性还有待加强,如添加try/catch模块
*/
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_SEND);
// intent.setType("image/jpg");
// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/sdcard/test.jpg")) );
// startActivity(intent);





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值