• 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开发者

  • 相关阅读:
    Android Studio使用
    VS.NET发送会议邮件程序原码
    C#中渐变色的代码实例,用于自绘菜单
    VS.NET获取某年某月的天数
    AJAX原理简要说明及实例
    ASP.NET下增加定时器功能
    VS.NET发送普通邮件原码
    保存xml到server实例
    VS.NET通过OUTLOOK发邮件
    利用IE打印的一点实例代码
  • 原文地址:https://www.cnblogs.com/luwenbin/p/3046426.html
Copyright © 2020-2023  润新知