Teach you to do Bluetooth chat application (ii)-Design plan

Source: Internet
Author: User

2nd Section Design Plan

After the function is determined, it is necessary to start the functional verification around the function, the layout of the interface design, and the planning of the program structure.

2.1 Technical Verification

Having selected the core functions to be done at this stage, we first need to do technical validation of them to see what methods can be implemented. The technical validation also allows us to discover a number of practical problems that we are unaware of in the brainstorming phase.

Now the mobile phone and mobile devices have Bluetooth as a standard configuration, it is often used with the peripheral small device data connection, such as Bluetooth selfie stick, Bluetooth speaker, Bluetooth keyboard, sports bracelet and so on, you can see that this is not a lot of data transmission need to maintain long-time communication equipment.

Bluetooth technology from the advent to now through a number of versions, now the most common mobile phone is Bluetooth 4.0.

As an application developer, you do not need to know a lot about Bluetooth technology related hardware knowledge. Google encapsulates all the Bluetooth features that software developers use, and is available to developers through the Android SDK. So as long as we know how to use the Bluetooth interface function provided in the Android SDK. As for how hardware is implemented, radio waves communicate with each other, and developers have absolutely no need to care.

To operate the Bluetooth device, we first get the object that operates the Bluetooth device BluetoothAdapter ,

BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();

At the same time, you need to use three system permissions,

<manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.anddle.anddlechat">        <uses-permission android:name="Android.permission.BLUETOOTH" />    <uses-permission android:name="Android.permission.BLUETOOTH_ADMIN" / >    <uses-permission android:name="Android.permission.ACCESS_COARSE_LOCATION" />......</manifest>

After that we can BluetoothAdapter use the real Bluetooth device and the software function to operate.

2.1.1 Device Discovery

A simple "Let the device Connect", actually contains a lot of hidden tasks.

2.1.1.1 Turn on Bluetooth

Users do not always turn on the Bluetooth device, because our application to use Bluetooth, if the user does not open the Bluetooth device, our program has to open it or prompt users to open it actively.

There are three ways to turn on the Bluetooth feature,

    1. Open with the switch provided by the Android system. For example, 设置->蓝牙 open in the interface,

    2. Use the Startup confirmation window in your app to Intent let the user choose whether to allow open,

      BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();//判断蓝牙功能是否打开if (!BTAdapter.isEnabled()) {    //没有打开,就启动确认窗口询问用户是否打开    new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivity(i);}
    3. Open the Bluetooth feature directly in the app without asking the user,

      BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();//判断蓝牙功能是否打开if (!BTAdapter.isEnabled()) {    ////没有打开,就直接打开    BTAdapter.enable();}
2.1.1.2 allowed to be found

After Bluetooth is turned on, the device is not necessarily able to find other Bluetooth devices, for security reasons, many devices Bluetooth switch even open, it is possible to prohibit other devices to find themselves.

For the sake of insurance, we need to set up the device to be discovered by another Bluetooth device.

    1. BluetoothAdapterthe getScanMode() method used to obtain whether the current Bluetooth can be detected;
    2. Through BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE the Intent Startup Inquiry window;
    3. BluetoothAdapter.EXTRA_DISCOVERABLE_DURATIONUsed to specify the time allowed to be discovered, for example, 120 indicates that 120 the Bluetooth device is allowed to be discovered by others in the next second, and if the value is set to 0, it can always be found;
BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();//判断是非可以被发现if(BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {    //启动窗口,询问用户是否可以设置成允许被发现    new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);    //可以一直被别的蓝牙设备发现    0);    startActivity(i);}
2.1.1.3 Search to connect devices

Search for a Bluetooth device that can be connected,

  1. Use BluetoothAdapter the startDiscovery() method to start the search device

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//如果正在搜索蓝牙设备,则停止搜索if (mBluetoothAdapter.isDiscovering()) {    mBluetoothAdapter.cancelDiscovery();}//开始搜索蓝牙设备mBluetoothAdapter.startDiscovery();
  2. When the search is started, a broadcast will be sent to the system BluetoothAdapter.ACTION_DISCOVERY_STARTED ;
    When the search is finished, a broadcast will be issued BluetoothAdapter.ACTION_DISCOVERY_FINISHED ;
    When a connected device is found, a broadcast is issued, BluetoothAdapter.ACTION_FOUND and the information of the connected device is placed in the corresponding intent of the broadcast;

    Therefore, you need to customize one BroadcastReceiver to receive these broadcasts,

    Private FinalBroadcastreceiver Mreceiver =NewBroadcastreceiver () {@Override     Public void OnReceive(context context, Intent Intent) {String action = intent.getaction ();if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//Get a device to connect from intentBluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device); }Else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals (ACTION)) {//Start searching for}Else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {//End of search}    }};
  3. The receiver uses the dynamic way, when the application launches the time to be registered, does not use the time to write off,

    //注册接收机new IntentFilter();filter.addAction(BluetoothDevice.ACTION_FOUND);filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mReceiver, filter);------------------------------------------//注销接收机unregisterReceiver(mReceiver);
2.1.1.4 Search Results show

Applications need a search of nearby devices, which can search the nearby devices, form a list for the user to choose, if the user chooses a device, then it will be to actively connect the device.

设置->蓝牙There is such a display on the interface,

However, our own chat application should also have a similar interface, so that users can choose the device, in the same application to complete the display and connectivity functions.

2.1.2 Device Connection

The connection of a Bluetooth device (as is the case with WiFi devices) can be divided into active and passive connections.

The connection to the device is Socket-套结字 achieved through. The so-called Socket "socket", like its English meaning, connects two different bodies through a socket receptacle.

Once the two entities are connected, the data can be transmitted through the socket.

/*******************************************************************/
* Copyright Notice
* This tutorial is only published in CSDN and the green Bean Network, other websites appear this tutorial is infringing.
/*******************************************************************/

2.1.2.1 Passive Connection

If the application does not take the initiative to find the surrounding equipment, do not actively connect to other devices, it can be a passive recipient, waiting for someone else's connection.

  1. Create one and BluetoothServerSocket need to assign him a name and UUID. The name can be arbitrarily assigned, the UUID has a certain knowledge. Bluetooth apps that use the same UUID can be discovered by each other.

    The UUID of a Bluetooth device can be divided into two large categories,

      1. A UUID that is uniformly specified by the Bluetooth standard. For example 00001101-0000-1000-8000-00805F9B34FB , this UUID represents蓝牙串口服务

      2. Custom UUID, Bluetooth app developers can "design" a uuid. This UUID cannot be the same as an already specified UUID, just to separate your Bluetooth app from other Bluetooth apps.

    The UUID concept of Bluetooth is a bit like the port number in network programming.
    For example, according to the provisions, the port number 23 is assigned to the FTP service to use, other FTP applications want to communicate with each other, not to guess what the other side of the port number, as long as the agreement has been stipulated in 23, we will abide by the line, the design of the application will never have problems.
    Developers can also specify an unknown port number for their application and do not need to interoperate with other applications.

    Here 蓝牙串口服务 's the UUID we're using.

    BluetoothAdapter BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();final"AnddleChat";final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");BluetoothServerSocket mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(            BT_NAME, BT_UUID);
  2. Start a thread-call it 监听线程 , in it, use BluetoothServerSocket the accept() method that waits for the other device to connect;

    BluetoothSocket socket = mServerSocket.accept();

    This is a blocking call. This means that once the function is executed accept() , it is waiting there and will not return. This is also the reason to put the wait connection alone on the listener thread execution.

    If the accept() function returns, there are two possibilities,

      1. There are other devices that make a connection request to themselves. accept()after the return, socket is connected to the device and connected devices established Socket , which is the program has been waiting;

      2. mServerSocketclose()function is called, resulting in accept() an exception being thrown,

        //别的地方关闭了BluetoothServerSocketmServerSocket.close()----------------------------------//监听线程try {    catch (IOException e) {    //正在监听会抛出异常}

After the above process, the listener thread receives the connection from other Bluetooth devices Socket .

2.1.2.2 Active Connection

After a Bluetooth device searches for nearby connected devices, you can proactively initiate connection requests to them.

    1. Through the address of the other, get the Bluetooth device,

      BluetoothAdapter BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddr);
    2. Create a connection request that you want to use to the UUID when you create it, and the UUID of the device that initiates the connection is the same as the UUID of the Socket device that passively accepts the connection, as if it were to adjust the send and accept to the same channel.

      final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");BluetoothSocket mSocket = device.createRfcommSocketToServiceRecord(BT_UUID);
    3. connect()initiate a connection request with a function that is a blocking call that is not sure of the return time, so a separate thread execution is required for it,

      //工作线程中执行mSocket.connect();

      Once the execution succeeds, we get the ability to communicate with other Bluetooth devices Socket .

2.1.3 Data exchange

After the connection is established, both parties begin exchanging data. Whether it is an active or passive connection, the exchange of data is Socket done previously.

  1. Gets the ability to read and send data. The Socket data exchanged is in binary form. So you can manipulate the data in a way that flows

    InputStream mInStream = mSocket.getInputStream();OutputStream mOutStream = mSocket.getOutputStream();

    InputStreamResponsible for reading from Socket the incoming data;
    OutputStreamResponsible for sending the data Socket out;

  2. InputStreamthe method used to read() read the data. This is a blocking method, only the connected party has the data sent over the time will be returned, and the data transmitted in the buffer parameters, the return value represents the length of the data bytes read.

    Once you have read it, you need to repeat read() the call to continue reading the next data, which is a cyclic process,

    //存放传入数据的数据区bytenewbyte[MAX_BUFFER_SIZE];//存放读取数据的字节长度int bytes;while (true) {    try {        //等待读取数据        bytes = mInStream.read(buffer);    catch (IOException e) {        //异常情况,例如Socket被关闭,对方断开连接        break;    }}

    When the place is closed Socket , an mInStream.read() exception is thrown,

    "' Java
    The socket was closed somewhere else.
    Msocket.close ()

Listening threads
try {
Waiting for data to be read
bytes = minstream.read (buffer);
} catch (IOException e) {
Abnormal conditions, such as the socket being closed
Break
}
"'

Because mInStream it was mSocket created, the relationship between the two has been established. So when you close mSocket mInStream it, you also get an effect, which throws an exception.

    1. OutputStreamthe method used to write() send the data

      mOutStream.write(data);

In Socket the process of use, many places can throw an exception, so in the design of the program structure later, we have to think about how to correspond to these anomalies.

2.2 Interface Design

After we have identified the functionality and conducted a technical survey, we can begin to design the application process based on the information we currently have.

The application process is divided into three parts,

2.2.1 Application Launch
    1. If the Bluetooth feature is not turned on, start the app and prompt to turn on the Bluetooth feature.

    2. If it cannot be discovered by other Bluetooth devices, it will be prompted to be discovered by other Bluetooth devices after launching the app.

    3. If the Bluetooth function is turned on and can be found by other devices, go to the main interface,

2.2.2 Device active connection and information sending process 2.2.3 Device passive connection and information sending process, 2.2.4 about Interface 2.3 program structure

Depending on the application's functionality and interface logic, the program structure is divided into three modules,

    1. The presentation and delivery of chat logs. Use one Activity - ChatActivity to accomplish this part of the work;
    2. Find a Bluetooth device that you can connect to, and let the user select the device to connect to. Use one Activity - DeviceListActivity to implement. When a user selects a device, it tells ChatActivity the result that the ChatActivity logical control of the connection is unified;
    3. Connection Management module. Connect Bluetooth devices, send messages between devices, disconnect, and so on, and communicate closely with the ConnectionManager module. The module provides an easy-to-use interface to the ChatActivity call.

Teach you to do Bluetooth chat application (ii)-Design plan

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.