zoukankan      html  css  js  c++  java
  • android ble 蓝牙4.0开发日志(二)

    写继承类相信大家都会吧,在这里我介绍下三星 怎么扫描le设备(写继承类之前,请先引用三星jar包,注意以外部jar包的方式引用也就是【Add External JARs】 ble_sunsang.jar,群共享有下载。)

    第一步我们要申明我们写的程序具备操作蓝牙的权限,在AndroidManifest.xml做如下声明。

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

    第二步我们在onCreate()方法里面 得到蓝牙设备

    定义蓝牙设备成员变量

    private BluetoothAdapter mBtAdapter;

    onCreate()方法初始化mBtAdapter;

    // 得到本地蓝牙设备。
            mBtAdapter = BluetoothAdapter.getDefaultAdapter();
            if(null != mBtAdapter)
            {
                //判断蓝牙是否是打开状态
                if(!mBtAdapter.isEnabled())
                {
                    //如果不是打开状态 打开蓝牙
                    mBtAdapter.enable();
                }
            }else
            {
                Toast.makeText(DeviceCorver.this, "找不到蓝牙设备!",
                        Toast.LENGTH_LONG).show();
            }

    第三步:调用mBtAdapter的mBtAdapter.startLeDiscovery();

    注意是startLeDiscovery() 不是 startDiscovery();

    mBtAdapter.startDiscovery();是不会扫描LE设备的。

    第四步:实例化一个BroadcastReceiver对象

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
                String action = intent.getAction();
    
                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    
                    BluetoothDevice device = (BluetoothDevice) intent
                            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    
                    if (device.getDeviceType() == 1
                            && device.getBondState() != BluetoothDevice.BOND_BONDED) {
    
                        //找到LE设备 写上你要处理的代码
                        
    
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                            .equals(action)) {
                          
                        }
    
                    }
                }
        };

    第五步:在onCreate里面注册广播

    // 注册开始发现广播。
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            this.registerReceiver(mReceiver, filter);
    
            // 当发现已完成注册的广播
            filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            this.registerReceiver(mReceiver, filter);

    等待扫描到LE设备的喜悦吧!!!  后续更新

    ble 4.0交流QQ群:293885474  加群备注:android ble开发者

  • 相关阅读:
    P4910 帕秋莉的手环
    P3216 [HNOI2011]数学作业
    洛谷 P2894 [USACO08FEB]酒店
    [网络流24题]魔术球问题
    [网络流24题]飞行员配对方案问题
    [网络流24题]最小路径覆盖问题
    洛谷 P1503鬼子进村
    BZOJ 3631: [JLOI2014]松鼠的新家
    洛谷 P2922 [USACO08DEC]秘密消息Secret Message
    洛谷 P1379 八数码难题
  • 原文地址:https://www.cnblogs.com/luwenbin/p/3046426.html
Copyright © 2011-2022 走看看