Android 连接到可编程设备

Android 连接到可编程设备,android,android-studio,bluetooth-lowenergy,Android,Android Studio,Bluetooth Lowenergy,所以我制作了这个应用程序,在这里我可以找到所有有名字的可移动设备。但是,我如何才能使其中一个特定字段,可单击并自动连接到设备,以便我可以开始从中写入/读取 适配器 公共类ListAdapter\u BTLE\u设备扩展了ArrayAdapter{ 活动; 国际布局资源; 阵列列表设备; 公用ListAdapter_BTLE_设备(活动、int资源、ArrayList对象){ super(activity.getApplicationContext(),资源,对象); 这个。活动=活动; layo

所以我制作了这个应用程序,在这里我可以找到所有有名字的可移动设备。但是,我如何才能使其中一个特定字段,可单击并自动连接到设备,以便我可以开始从中写入/读取

适配器

公共类ListAdapter\u BTLE\u设备扩展了ArrayAdapter{
活动;
国际布局资源;
阵列列表设备;
公用ListAdapter_BTLE_设备(活动、int资源、ArrayList对象){
super(activity.getApplicationContext(),资源,对象);
这个。活动=活动;
layoutResourceID=资源;
设备=对象;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
if(convertView==null){
充气机=
(LayoutFlater)activity.getApplicationContext().getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
convertView=充气机。充气(layoutResourceID,父项,false);
}
BTLE_Device=devices.get(位置);
String name=device.getName();
字符串地址=device.getAddress();
int rssi=device.getRSSI();
TextView BLE_name=(TextView)convertView.findViewById(R.id.BLE_name);
if(name!=null&&name.length()>0){
BLE_name.setText(device.getName());
}
否则{
BLE_name.setText(“无名称”);
}
TextView BLE_rssi=(TextView)convertView.findViewById(R.id.BLE_rssi);
BLE_rssi.setText(“rssi:+Integer.toString(rssi));
TextView BLE_macaddr=(TextView)convertView.findViewById(R.id.BLE_macaddr);
if(address!=null&&address.length()>0){
BLE_macaddr.setText(“MAC地址:+device.getAddress());
}
否则{
BLE_macaddr.setText(“无地址”);
}
返回视图;
}
}
编辑

我想我现在可能与关贸总协定有关,所以我所做的是。。 首先,我从main活动中获取MAC addr,然后将其保存在intent中,并在单击时启动另一个活动。 在这里,我做了以下工作
DeviceAddress=intent.getStringExtra(MainActivity.EXTRAS\u BLE\u地址)

BluetoothDevice设备=mBluetoothAdapter.getRemoteDevice(DeviceAddress)

device.connectGatt(this,false,mGattCallback)

当我调用connectGatt时,它会打印消息
Log.d(标记,“连接状态:1”),这是正确的方法吗


私有BluetoothGattCallback mGattCallback=新BluetoothGattCallback(){
@RequiresApi(api=Build.VERSION\u code.JELLY\u BEAN\u MR2)
@凌驾
连接状态更改的公共无效(蓝牙gatt gatt、int状态、int新闻状态){
Log.d(标记,“连接状态更改:“+status+”->“+connectionState(newState));
if(status==BluetoothGatt.GATT\u SUCCESS&&newState==BluetoothProfile.STATE\u CONNECTED){
/*
*一旦成功连接,我们接下来必须发现网络上的所有服务
*设备之前,我们可以读写它们的特性。
*/
Log.d(标记“连接状态:1”);
关贸总协定。发现服务();
}else if(status==BluetoothGatt.GATT\u SUCCESS&&newState==BluetoothProfile.STATE\u DISCONNECTED){
/*
*如果在任何时候我们断开连接,发送消息清除天气值
*用户界面之外
*/
Log.d(标签“连接状态:2”);
}否则如果(状态!=蓝牙GATT.GATT\U成功){
/*
*如果在任何阶段出现故障,只需断开连接即可
*/
Log.d(标签“连接状态:3”);
关贸总协定;
}
}

您可以将视图添加到支架上,并为其设置单击侦听器。视图可以是围绕显示卡(或您使用的任何东西)的透明矩形


我建议您深入阅读有关BLE用法的内容。在“单击侦听器”上,您可以将连接请求排队。

您可以向支架添加一个视图,并为其设置一个单击侦听器。视图可以是显示卡周围的透明矩形(或任何您使用的)


我建议您深入阅读有关BLE使用的内容。在“单击侦听器”上,您可以将连接请求排队。

要首先连接到设备,您必须执行BLE扫描,该扫描(如果您使用启动程序代码)运行回调,并将其添加到找到的设备列表中

在中添加一个筛选器,以仅允许您正在查找的设置设备。当BLE播发最多31字节的数据包时,您应该在此处包含一些识别您的设备的数据,例如制造商id或数据等。或者,如果您正在处理一个简单的项目,您可以通过编程在设备地址中硬编码


然后,当从扫描中发现此设备时,您可以停止您的BLE扫描并自动排队连接请求。这将要求发出GATT请求,从而授予您对GATT服务的访问权,从而允许您访问设备上的特征。

要先连接到设备,您必须执行BLE扫描,其中(如果您正在使用启动程序代码)运行回调并将其添加到找到的设备列表中

在中添加一个筛选器,以仅允许您正在查找的设置设备。当BLE播发最多31字节的数据包时,您应该在此处包含一些识别您的设备的数据,例如制造商id或数据等。或者,如果您正在处理一个简单的项目,您可以通过编程在设备地址中硬编码

然后,当从扫描中发现此设备时,您可以停止BLE扫描并自动排队连接请求。这将要求发出GATT请求,从而授予您访问GATT服务的权限,从而访问设备上的特征

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
dependencies {
        implementation 'com.github.niedev:BluetoothCommunicator:1.0.6'
}
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
    android:name="com.bluetooth.communicatorexample.Global"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:largeHeap="true"
    android:theme="@style/Theme.Speech">
    <activity android:name="com.bluetooth.communicatorexample.MainActivity"
        android:configChanges="orientation|screenSize">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
((custom class name) getApplication()).getBluetoothCommunicator();
bluetoothCommunicator = new BluetoothCommunicator(this, "device name", BluetoothCommunicator.STRATEGY_P2P_WITH_RECONNECTION);
bluetoothCommunicator.addCallback(new BluetoothCommunicator.Callback() {
    @Override
    public void onBluetoothLeNotSupported() {
        super.onBluetoothLeNotSupported();
        
        Notify that bluetooth low energy is not compatible with this device
    }
   
    @Override
    public void onAdvertiseStarted() {
        super.onAdvertiseStarted();

        Notify that advertise has started, if you want to do something after the start of advertising do it here, because
        after startAdvertise there is no guarantee that advertise is really started (it is delayed)
    }

    @Override
    public void onDiscoveryStarted() {
        super.onDiscoveryStarted();

        Notify that discovery has started, if you want to do something after the start of discovery do it here, because
        after startDiscovery there is no guarantee that discovery is really started (it is delayed)
    }

    @Override
    public void onAdvertiseStopped() {
        super.onAdvertiseStopped();

        Notify that advertise has stopped, if you want to do something after the stop of advertising do it here, because
        after stopAdvertising there is no guarantee that advertise is really stopped (it is delayed)
    }

    @Override
    public void onDiscoveryStopped() {
        super.onDiscoveryStopped();

        Notify that discovery has stopped, if you want to do something after the stop of discovery do it here, because
        after stopDiscovery there is no guarantee that discovery is really stopped (it is delayed)
    }

    @Override
    public void onPeerFound(Peer peer) {
        super.onPeerFound(peer);
        
        Here for example you can save peer in a list or anywhere you want and when the user
        choose a peer you can call bluetoothCommunicator.connect(peer founded) but if you want to
        use a peer for connect you have to have peer updated (see onPeerUpdated or onPeerLost), if you use a
        non updated peer the connection might fail
        instead if you want to immediate connect where peer is found you can call bluetoothCommunicator.connect(peer) here
    }

    @Override
    public void onPeerLost(Peer peer){
        super.onPeerLost(peer);
        
        It means that a peer is out of range or has interrupted the advertise,
        here you can delete the peer lost from a eventual collection of founded peers
    }

    @Override
    public void onPeerUpdated(Peer peer,Peer newPeer){
        super.onPeerUpdated(peer,newPeer);

        It means that a founded peer (or connected peer) has changed (name or address or other things),
        if you have a collection of founded peers, you need to replace peer with newPeer if you want to connect successfully to that peer.

        In case the peer updated is connected and you have saved connected peers you have to update the peer if you want to successfully
        send a message or a disconnection request to that peer.
    }

    @Override
    public void onConnectionRequest(Peer peer){
        super.onConnectionRequest(peer);

        It means you have received a connection request from another device (peer) (that have called connect)
        for accept the connection request and start connection call bluetoothCommunicator.acceptConnection(peer);
        for refusing call bluetoothCommunicator.rejectConnection(peer); (the peer must be the peer argument of onConnectionRequest)
    }

    @Override
    public void onConnectionSuccess(Peer peer,int source){
        super.onConnectionSuccess(peer,source);

        This means that you have accepted the connection request using acceptConnection or the other
        device has accepted your connection request and the connection is complete, from now on you
        can send messages or data (or disconnection request) to this peer until onDisconnected

        To send messages to all connected peers you need to create a message with a context, a header, represented by a single character string
        (you can use a header to distinguish between different types of messages, or you can ignore it and use a random
        character), the text of the message, or a series of bytes if you want to send any kind of data and the peer you want to send the message to
        (must be connected to avoid errors), example: new Message(context,"a","hello world",peer);
        If you want to send message to a specific peer you have to set the sender of the message with the corresponding peer.

        To send disconnection request to connected peer you need to call bluetoothCommunicator.disconnect(peer);
    }

    @Override
    public void onConnectionFailed(Peer peer,int errorCode){
        super.onConnectionFailed(peer,errorCode);

        This means that your connection request is rejected or has other problems,
        to know the cause of the failure see errorCode (BluetoothCommunicator.CONNECTION_REJECTED
        means rejected connection and BluetoothCommunicator.ERROR means generic error)
    }

    @Override
    public void onConnectionLost(Peer peer){
        super.onConnectionLost(peer);

        This means that a connected peer has lost the connection with you and the library is trying
        to restore it, in this case you can update the gui to notify this problem.

        You can still send messages in this situation, all sent messages are put in a queue
        and sent as soon as the connection is restored
    }

    @Override
    public void onConnectionResumed(Peer peer){
        super.onConnectionResumed(peer);
        
        Means that connection lost is resumed successfully
    }

    @Override
    public void onMessageReceived(Message message,int source){
        super.onMessageReceived(message,source);

        Means that you have received a message containing TEXT, for know the sender you can call message.getSender() that return
        the peer that have sent the message, you can ignore source, it indicate only if you have received the message
        as client or as server
    }

    @Override
    public void onDataReceived(Message data,int source){
        super.onDataReceived(data,source);

        Means that you have received a message containing DATA, for know the sender you can call message.getSender() that return
        the peer that have sent the message, you can ignore source, it indicate only if you have received the message
        as client or as server
    }

    @Override
    public void onDisconnected(Peer peer,int peersLeft){
        super.onDisconnected(peer,peersLeft);

        Means that the peer is disconnected, peersLeft indicate the number of connected peers remained
    }

    @Override
    public void onDisconnectionFailed(){
        super.onDisconnectionFailed();

        Means that a disconnection is failed, super.onDisconnectionFailed will reactivate bluetooth for forcing disconnection
        (however the disconnection will be notified in onDisconnection)
    }
});
bluetoothCommunicator.startAdvertising();
bluetoothCommunicator.startDiscovery();