android 蓝牙开发

要学习蓝牙先认识

  一RFCOMM通道:

  RFCOMM协议

  一个基于欧洲电信标准协会ETSI07.10规程的串行线性仿真协议。此协议提供RS232控制和状态信号,如基带上的损坏,CTS以及数据信号等,为上层业务(如传统的串行线缆应用)提供了传送能力。

  RFCOMM是一个简单传输协议,其目的是针对如何在两个不同设备上的应用之间保证一条完整的通信路径,并在它们之间保持一通信段。

  RFCOMM协议概述

  RFCOMM通信段

  RFCOMM是为了兼容传统的串口应用,同时取代有线的通信方式,蓝牙协议栈需要提供与有线串口一致的通信接口而开发出的协议。RFCOMM协议提供对基于L2CAP协议的串口仿真,基于ETSI07.10。可支持在两个BT设备之间同时保持高达60路的通信连接。

  目的:

  在两个不同设备(通信设备的两端)上的应用之间保证一条完整的通信路径,并在他们之间保持一通信段。下图是一条完整的通信路径。

  RFCOMM只针对直接互连设备之间的连接,或者是设备与网络接入设备之间的互连。通信两端设备必须兼容于RFCOMM协议,有两类设 备:DTE (Data Terminal Endpoint,通信终端,如PC,PRINTER)和DCE (Data Circuit Endpoint,通信段的一部分,如Modem)。此两类设备不作区分。

  RFCOMM服务

  RFCOMM仿真RS232串口,仿真过程包括非数据通路状态的传输,RFCOMM内置空Modem仿真标准框架。

  RFCOMM中的仿真RS-232通路

  多串口仿真

  两个采用RFCOMM通信的BT设备有可能同时打开多个串口,RFCOMM支持同时打开60个端口。

  认识二:MAC硬件地址

  MAC(Medium/MediaAccess Control, 介质访问控制)MAC地址是烧录在NetworkInterfaceCard(网卡,NIC)里的.MAC地址,也叫硬件地址,是由48比特长(6字 节),16进制的数字组成.0-23位叫做组织唯一标志符(organizationally unique,是识别LAN(局域网)节点的标识.24-47位是由厂家自己分配。其中第40位是组播地址标志位。网卡的物理地址通常是由网卡生产厂家烧 入网卡的EPROM(一种闪存芯片,通常可以通过程序擦写),它存储的是传输数据时真正赖以标识发出数据的电脑和接收数据的主机的地址。

  也就是说,在网络底层的物理传输过程中,是通过物理地址来识别主机的,它一般也是全球唯一的。比如,著名的以太网卡,其物理地址是 48bit(比特位)的整数,如:44-45-53-54-00-00,以机器可读的方式存入主机接口中。以太网地址管理机构(除了管这个外还管别的)

  (IEEE)(IEEE:电气和电子工程师协会)将以太网地址,也就是48比特的不同组合,分为若干独立的连续地址组,生产以太网网卡的厂家就购买其中一组,具体生产时,逐个将唯一地址赋予以太网卡。

  形象的说,MAC地址就如同我们身份证上的身份证号码,具有全球唯一性。

  步骤一:Setting Up Bluetooth

  通过BluetoothAdapter得到蓝牙的Activity

  发送蓝牙连接意图

  通过e onActivityResult()得到蓝牙连接意图

  步骤二: Finding Devices

  通过得到开启蓝牙用户名和MAC地址

  配对蓝牙

  步骤三:连接蓝牙

  就像java的聊天系统一样用一个蓝牙手机当服务器,一个当客户端,在用一个类当做连接的管理类就行了

1、 在AndroidManifest.xml文件中注册蓝牙
  !-- 注册蓝牙 --
  uses-permission android:name="android.permission.BULETOOTH"/
  !-- 注册蓝牙操作 --
  uses-permission android:name="android.permission.BULETOOTH_ADMIN"/
  2、 编写界面描述文件
  ?xml version="1.0" encoding="utf-8"?
  LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   
  TextView 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="@string/hello"
   /
  Button
   android:id="@+id/btn_select_bluetooth"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="搜索周围以配对蓝牙"
   /
  Button
   android:id="@+id/btn_discoverable"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="设置蓝牙可见性"
   /
  TextView
   android:id="@+id/txt_resurce"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   /
  /LinearLayout
  3、 编写代码
  package com.yazhou.activity;
  
  import java.util.Iterator;
  import java.util.Set; 
  import android.app.Activity;
  import android.bluetooth.BluetoothAdapter;
  import android.bluetooth.BluetoothDevice;
  import android.content.Intent;
  import android.os.Bundle;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.TextView;
  
  public class Main extends Activity {
   private TextView txt_resurce;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   //获取文本控件
   txt_resurce = (TextView)findViewById(R.id.txt_resurce);
   //获取按钮控件
   Button btn_select_bluetooth = (Button)findViewById(R.id.btn_select_bluetooth);
   //为按钮添加单击事件
   btn_select_bluetooth.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
   //获取蓝牙本地对象
   BluetoothAdapter bluetoothadapter = BluetoothAdapter.getDefaultAdapter();
   //判断BluetoothAdapter是否为空,如果为空,表明本机没有蓝牙设备
   if(bluetoothadapter!=null){
   txt_resurce.setText("本机有蓝牙设备");
   //判断蓝牙是否开启
   if(!bluetoothadapter.isEnabled()){
   //创建intent对象
   Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
   startActivity(intent);
   }
   //获取已经配对的蓝牙设备
   Set bluetoothdevices = bluetoothadapter.getBondedDevices();
   //判断是否有已经配对的蓝牙
   if(bluetoothdevices.size()>0){
   //迭代输出已经配对的蓝牙设备
   for (Iterator iterator = bluetoothdevices.iterator(); iterator
   .hasNext();) {
   BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator
   .next();
   txt_resurce.setText("已经配对的蓝牙名:"+bluetoothDevice.getName()+"地址:"+bluetoothDevice.getAddress());
   }
   }
   }else{
   txt_resurce.setText("本机没有蓝牙设备");
   }
   }
   });
   //获取设置蓝牙可见性的按钮控件
   Button btn_discoverable = (Button)findViewById(R.id.btn_discoverable);
   //为按钮添加单击事件
   btn_discoverable.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
   //获取intent对象
   Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
   //设置蓝牙可见性持续的时间,超过300秒的,按300秒算
   intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
   //启动intent
   startActivity(intent);
   }
   });
   }




  private String strText = "";
    // Create a BroadcastReceiver for ACTION_FOUNDprivate
       
    private BluetoothAdapter bluetoothadapter;
    public void getBlueToothNeighbor() {
        strText = "";
        final BroadcastReceiver mReceiver = new BroadcastReceiver()
        {   
            public void onReceive(Context context, Intent intent)
            {       
                String action = intent.getAction();       
                // When discovery finds a device       
                if (BluetoothDevice.ACTION_FOUND.equals(action))
                {           
                    // Get the BluetoothDevice object from the Intent           
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);           
                    // Add the name and address to an array adapter to show in a ListView 

                    Log.i("GetBlueTooth", "Name:"+device.getName() +"-Address:"+device.getAddress());    
                    strText = strText + device.getName() + ":[" + device.getAddress() + "]##\n";
                    tv.setText("Find Bloo:: "+strText);
                    //String str = device.getAddress();
                    //str = device.getName();
                } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                    Log.i("GetBlueTooth", "Started discovery");    
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Log.i("GetBlueTooth", "Finished discovery");    
                    tv.setText("Find Bloo:: "+strText);
                    strText = "";
                    bluetoothadapter.startDiscovery();
                    //bluetoothadapter.disable();
                }
            }
        };
        //String strText = "";
        bluetoothadapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothadapter!=null){
            tv.setText("Please Wait.....");
//            if(!bluetoothadapter.isEnabled()){
//                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                startActivity(intent);
//            }
// 无须弹出窗口询问,自动Enable.....别忘了调用disable()方法
            bluetoothadapter.enable();
//            Set<BluetoothDevice> bluetoothdevices = bluetoothadapter.getBondedDevices();
//            if(bluetoothdevices.size()>0){
//                for (Iterator<BluetoothDevice> iterator = bluetoothdevices.iterator(); iterator.hasNext();) {
//                    BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();
//                    strText = bluetoothDevice.getName() + ":[" + bluetoothDevice.getAddress() + "]##\n";
//                }
//                tv.setText("Find Bloo:: "+strText);
//            }
         // Register the BroadcastReceiver

// 自动扫描附近蓝牙设备
            bluetoothadapter.startDiscovery();
            Log.i("GetBlueTooth", "Starting 1");    
            IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            IntentFilter filterStop = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            registerReceiver(mReceiver, filterFound);
            registerReceiver(mReceiver, filterStart);
            registerReceiver(mReceiver, filterStop);
            Log.i("GetBlueTooth", "Starting 2");    
            //IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            //registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
            Log.i("GetBlueTooth", "Starting 3");       

        }else{
            tv.setText("No BlueTooth Device");
        }



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值