蓝牙和WIFI

蓝牙 | 蓝牙连接过程

2019-12-30  本文已影响0人  力卉编程

调用顺序

1、获得BluetoothAdapter
//获得BluetoothAdapter,对任何Bluetooth Activity都需要先获得。获取方法是调用getDefaultAdapter()方法。
//getDefaultAdapter方法定义于<frameworks/base/core/java/android/bluetooth/bluetoothAdapter.java>
​BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

public static synchronized BluetoothAdapter getDefaultAdapter() {
        if (sAdapter == null) {
            IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
            if (b != null) {
                IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
                sAdapter = new BluetoothAdapter(managerService);
            } else {
                Log.e(TAG, "Bluetooth binder is null");
            }
        }
        return sAdapter;
    }
BluetoothAdapter(IBluetoothManager managerService) {
 
        if (managerService == null) {
            throw new IllegalArgumentException("bluetooth manager service is null");
        }
        try {
            mService = managerService.registerAdapter(mManagerCallback);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        mManagerService = managerService;
        mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
        mToken = new Binder();
    }

2、Enable Bluetooth

//isEnable定义于<frameworks/base/core/java/android/bluetooth/bluetoothAdapter.java>
if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
@RequiresPermission(Manifest.permission.BLUETOOTH)
    public boolean isEnabled() {
        try {
            synchronized(mManagerCallback) {
                if (mService != null) return mService.isEnabled();
            }
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    }

3、查询配对设备

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}
//getBondedDevices定义于<frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java>
 ​    public Set<BluetoothDevice> getBondedDevices() {
        if (getState() != STATE_ON) {
            return toDeviceSet(new BluetoothDevice[0]);
        }
        try {
            synchronized(mManagerCallback) {
                if (mService != null) return toDeviceSet(mService.getBondedDevices());
            }
            return toDeviceSet(new BluetoothDevice[0]);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    }

4、调用startDiscovery()启动设备发现。该过程是异步进行的,立即返回的值表明设备发现是否启动。这一过程差不多需要12秒,然后对每一个查到的设备进行页扫以获得其Bluetooth名称。

为了接收发现每一个设备的信息,应用程序必须为ACTION_FOUND intent注册一个BroadcastReceiver,针对每一个设备,系统将会广播ACTION_FOUND intent内容。该intent包括EXTRA_DEVICE和EXTRA_CLASS标志,分别包含了BluetoothDevice和BluetoothClass信息。

//BluetoothDevice这个类定义于<frameworks/base/core/java/android/bluetooth/BluetoothDevice.java>
 ​// Create a BroadcastReceiver for ACTION_FOUND
private 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
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

5、使能发现能力

如果想使设备自身能够被其它设备发现,调用startActivityForResult(Intent, int)方法,并传递ACTION_REQUEST_DISCOVERABLE intent。这将通过系统设置发出使能发现请求,缺省状态下,设备被发现的时间在120s内。但是可以通过EXTRA_DISCOVERABLE_DURATION进行修改该时长。最长可为3600s。


 ​Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

这时将弹出一个对话框,请求用户允许设备发现,如果用户使能,则onActivityResult()回调将被调用。设备将在设定的时间内可被发现。如果想在发现模式变化时被通知,需要为ACTION_SCAN_MODE_CHANGED Intent注册BroadcastReceiver,这将包括EXTRA_SCAN_MODE和EXTRA_PREVIOUS_SCAN_MODE字段,其分别指示的是新旧扫描模式。可能的值是SCAN_MODE_CNONNECTABLE_DISCOVERABLE和SCAN_MODE_CONNECTABLE或者SCAN_MODE_NONE。

6、连接设备

为了将两个设备上的应用程序建立连接,必须实现server端和client端,这时因为一个设备必须打开sever socket,而另一个设备必须初始化连接(使用server设备的MAC地址初始化连接)。只有当server和client在相同的RFCOMM通道有一个已连接的BluetoothSocket。到此,每一个设备能够获得输入和输出流,数据传输可以进行了,数据传输在管理连接里叙述。此节描述如何在两个设备上初始化连接。

server和client 设备用不同的方式获得BluetoothSocket。server端在连接建立被接受时获得,client端在为server端打开RFCOMM通道是获得。

一个实现的技术是自动将每一个设备作为server,如此可以让每一个设备有打开并用于侦听的server socket。然后两个设备之间可以互连。

7、作为server连接

当连接两个设备时,其中一个设备必须通过保持一个打开的BluetoothServerSocket作为server角色。server socket的作用是侦听接收到的连接请求,当其中一方接受时,提供一个建立连接的BluetoothScoket。当BluetoothSocket从BluetoothServerSocket获得时,除非希望接收更多的连接,否则BluetoothServerSocket应该被丢弃。

建立server socket和接收连接的基本步骤如下:

String是服务的名称,系统会自动将该服务写入到服务发现协议(Service Discovery Protocol,SDP)。UUID也在SDP里并且是client连接通过的基础。

阻塞调用,当建立连接完成或者遇到特殊情况将会返回。只有当远端设备使用和这里的侦听socket一致的UUID发送连接请求时,这个连接才是可被接受的。当连接建立后accept()将会返回连接的BluetoothSocket()。

这将释放server端socket。但并不关闭由accept()返回的建立连接的BluetoothSocket。和TCP/IP不同的是,RFCOMM每个通道在一个时刻只允许一个连接的client。主activity并不适合使用阻塞的accept,通常在thread中实现。

​private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;
 
    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }
 
    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                mmServerSocket.close();
                break;
            }
        }
    }
 
    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

8、连接client

为了和远端的设备相连,首先应获得表示远端设备的BluetoothDevice对象,需要使用BluetoothDevice 接收BluetoothSocket 并且初始化连接。

主要过程如下:

9、连接管理

当多个设备成功建立连接时,每一个设备都有一个连接的BluetoothSocket。通过其可以让设备间共享数据。使用BluetoothSocket,传递任意数据的过程是比较简单的。

 ​private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
 
    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
 
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
 
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
 
    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()
 
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
 
    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }
 
    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

其它:如何使用profile

profile是两个设备基于蓝牙通信的无线接口规范。一个例子是Hands-Free profile。对于手机连接到无线耳机情景,两个设备必须都支持Hands-Free profile。
可以使用BluetoothProfile创建一个特殊自有的profile。安卓蓝牙API支持以下Bluetooth profile。
Headset。耳机和手机见的profile,BluetoothHeadset类,A2DP, BluetoothA2dp Health Device。
使用profile的基本步骤如下

​BluetoothHeadset mBluetoothHeadset;
 
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
 
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = (BluetoothHeadset) proxy;
        }
    }
    public void onServiceDisconnected(int profile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null;
        }
    }
};
 
// ... call functions on mBluetoothHeadset
 
// Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);

完~~
文 | 力卉编程

上一篇下一篇

猜你喜欢

热点阅读