Mobile phone Bluetooth app for smart home: Implementing data transfer with CC2530

Source: Internet
Author: User

Graduation design is to do the topic of smart home, to do a mobile phone Bluetooth app, and the next computer to achieve data transmission; I've never done Android before, but I'm pretty good with qt,c++, so I use eclipse to feel quite handy, and the Java language is very similar to C + + in many places, so I personally feel , C + + people, Java is certainly not a problem.

Not familiar with Java, you can refer to my article Java syntax: different from C + + places. You are not familiar with the Eclipse programming environment. Refer to the Android Programming Authority Guide-digital version is perfect for developers who just contacted Android, which is very detailed, download link: Click on the Open link http://download.csdn.net/detail/ heart18335101121/9511224 bluetooth app source download link: Click on the Open link http://download.c sdn.net/detail/heart18335101121/9511227

Original address: http://developer.android.com/guide/topics/wireless/bluetooth.html

The Android platform supports the Bluetooth network protocol stack, which realizes the wireless transmission of data between Bluetooth devices. This document describes how to use the Bluetooth API provided by the Android platform to communicate with blue-pressed devices. Bluetooth has two kinds of point-to-point and multipoint connection functions.
Using the Bluetooth API, you can do this:
* Search for Bluetooth devices
* Query for paired devices from a local Bluetooth adapter
* Establish RFCOMM Channel
* Connect to other devices via service discovery
* Transfer data between devices
* Manage multiple connection Basics

This document describes how to use the Android Bluetooth API to complete the four essential tasks, using Bluetooth for device communication, consisting mainly of four parts: Bluetooth settings, search devices (paired or visible), connect, transmit data.
All Bluetooth APIs are in the Android.bluetooth package. The main requirements for implementing these features are the following classes and interfaces:

Bluetoothadapter
Represents the local Bluetooth adapter (Bluetooth transmitter) and is the gateway to all Bluetooth interactions. It allows you to search for other Bluetooth devices, query the list of paired devices, create Bluetoothdevice from a known MAC address, and create bluetoothserversocket to listen for traffic from other devices.

Bluetoothdevice
Represents a remote Bluetooth device that uses it to request a remote Bluetooth device to connect or get the name, address, type, and binding status of the remote Bluetooth device. (The information is encapsulated in Bluetoothsocket).

Bluetoothsocket
Represents a Bluetooth socket interface (similar to a socket in TCP), which is a connection point that the application communicates with other Bluetooth devices through input and output streams.

Bluetoothserversocket
On behalf of the Open service connection to listen for possible connection requests (belonging to the server side), to connect two Bluetooth devices, you must have a device open a service socket as a server. The Blueboothserversocket class returns a bluetoothsocket when a remote device initiates a connection request and is already connected.

Bluetoothclass
Describes the characteristics of a device (profile) or what services (service) can be provided by Bluetooth on the device, but not trusted. For example, a device is a telephone, a computer, or a handheld device; a device can provide audio/telephony services. You can use it to make some hints on the UI.
Bluetoothprofile

Bluetoothheadset
Provide support for mobile phone using Bluetooth headset. This includes both Bluetooth headset and hands-free (V1.5) mode.

Bluetootha2dp
Defines high quality audio, which can be transferred from one device to another Bluetooth connection. "A2DP" represents the advanced audio allocation mode.

Bluetoothhealth
On behalf of the medical device configuration agent-controlled Bluetooth service

Bluetoothhealthcallback
An abstract class that uses the implementation Bluetoothhealth callback. You must extend this class and implement a callback method to receive the update application's registration status and the Bluetooth channel state changes.

Bluetoothhealthappconfiguration
Represents an application configuration, Bluetooth medical third party application registration and remote Bluetooth medical equipment Exchange.

Bluetoothprofile.servicelistener
An interface (that is, running a specific profile, internal services) when they are notified to Bluetoothprofile IPX clients when they have connected or disconnected from the service. Bluetooth Permissions

In order to use Bluetooth in your application, at least two permissions must be declared in Androidmanifest.xml: Bluetooth (any Bluetooth-related API will use this permission) and bluetooth_admin (device search, Bluetooth settings, etc.).

In order to perform Bluetooth communications, such as connection requests, the receive connection and transfer data must have Bluetooth permissions.

You must require Bluetooth_admin permissions to start the device discovery or manipulate the Bluetooth settings. Most applications need this privilege capability to discover local Bluetooth devices. This permission grants additional capabilities that should not be used unless the application is a "power management" that will be modified according to user requirements for Bluetooth settings

Note: To request Bluetooth_admin, you must have Bluetooth first.

Declare Bluetooth permissions in your application manifest file. For example:

1
2
3
4
<manifest > <uses-permissionandroid:name= "Android.permission.BLUETOOTH"/>
...
</manifest>

Declare the application permissions by viewing <uses-permission> data to get more information. Bluetooth Settings

Before your application communicates via Bluetooth, you need to verify that the device supports Bluetooth, and if so, make sure it is turned on.

If it is not supported, the Bluetooth feature is not available. If Bluetooth is supported but not available, you are just about to request Bluetooth in your application. This will be done in two steps, using Bluetoothadapter.

1. Get Bluetoothadapter

All Bluetooth activity requests Bluetoothadapter, in order to get Bluetoothadapter, call static method Getdefaultadapter (). This returns a bluetoothadapter that represents the device's own Bluetooth adapter (Bluetooth radio). This Bluetooth adapter is applied throughout the system, and your application can interact with this object. If Getdefaultadapter () returns NULL, the device does not support Bluetooth. For example:

1
2
3
4
Bluetoothadapter mbluetoothadapter = Bluetoothadapter.getdefaultadapter (); if (Mbluetoothadapter =null) {///Device does not support Bluetooth}

2. Turn on Bluetooth

Secondly. You need to make sure that Bluetooth is available. Check to see if Bluetooth is currently available by IsEnabled (). If this method returns false, Bluetooth is not available. In order to request Bluetooth use, call Startactivityforresult () with the action_request_enable action intent. enabling Bluetooth through the system settings makes a request (does not stop the Bluetooth application). For example:

1
2
3
4
if (!mbluetoothadapter.isenabled ()) {
Intent enablebtintent =new Intent (bluetoothadapter.action_request_enable);
Startactivityforresult (Enablebtintent, REQUEST_ENABLE_BT);}

! [Http://developer.android.com/images/bt_enable_request.png]

The dialog box displays the request to use Bluetooth permissions. If the response is "Yes", your application will be able to use Bluetooth after the process completes (or fails).
The REQUEST_ENABLE_BT constant is passed to the Startactivityforresult () as an integral type (the value must be greater than 0), and the system is passed back to you, in your Onactivityresult () as the Requestcode parameter of the implementation.

If Bluetooth is invoked successfully, your activity will receive RESULT_OK results in Onactivityresult (), if Bluetooth cannot be used because of an error (or the user responds "NO"), the result returns result_canceled.

In addition to passing the Onactivityresult (), you can also monitor the action_state_changed to see if the Bluetooth status changes by listening to the broadcast intent. This intent contains extra_state,extra_previous_state two fields, representing the old and new states respectively. The possible values are state_turning_on, state_on, State_turning_off, and State_off.

Small stickers: Enabling discoverability will automatically enable Bluetooth. If you plan to perform Bluetooth activity before you always make the device visible, you can skip step 2 above. See Enabling Discoverability. Search Device

You can use Bluetoothadapter to locate a remote Bluetooth device through a device search or a query pairing device.

Device Discovery (Device search) is the process of scanning for locally enabled Bluetooth devices and requesting some information from a search device (sometimes receiving a similar "discovering", "inquiring" or "scanning"). However, a local Bluetooth device that is found only responds to a discovery request after the discovered feature is turned on, and the response information includes the device name, class, and unique MAC address. The device that initiates the search can use this information to initialize the connection to the device being discovered.
Once the first connection with the remote device is established, a pairing request is automatically submitted to the user. If the device is paired, the basic information (name, class, MAC address) of the pairing device is saved, and the Bluetooth API is used to read the information. With the MAC address of a known remote device, the connection can be initialized at any time without having to complete the search first (assuming, of course, that the remote device is in a connected space).

Remember that pairing and joining are two different concepts:

Pairing means that two devices are aware of each other's existence, sharing a chain Lu Ling (Link-key) that identifies identities, and can establish an encrypted connection with each other.

The connection means that both devices now share a RFCOMM channel that can transmit data to each other.

Currently, the Android Bluetooth API ' s requires the device to be paired before establishing the Rfcomm channel (pairing is done automatically when initializing an encrypted connection using the Bluetooth API).

The following describes how to query for paired devices and search for new devices.

Note: The Android power device is not found by default. Users can use system settings to allow it to be discovered within a limited amount of time, or to require users to be found in applications. Find matching devices

Before searching for a device, it is worthwhile to query the pairing device to see if the device you need is already there, and you can call Getbondeddevices () to do it, which returns a result set that describes the pairing device Bluetoothdevice. For example, you can use Arrayadapter to query all pairing devices and then display all device names to the user:

1
2
3
4
5
6 7 8 9
set<bluetoothdevice> paireddevices = mbluetoothadapter.getbondeddevices ();/If There are paired devicesif (Paireddevices.size () >0) {//Loop through paired devicesfor (Bluetoothdevice device:paireddevices) {//ADD the name and address to a ListView
        Marrayadapter.add (device.getname () + "n" + device adapter) . getaddress ());};

The only information that needs to be used to initialize a connection in the Bluetoothdevice object is the MAC address. Scan Device

To start the search device, simply call StartDiscovery (). The function is asynchronous, returns immediately after the call, and returns a value that indicates whether the search started successfully. The search process typically includes a 12-second query scan followed by a page showing the search to the device's Bluetooth name.

An application can register a broadcastreceiver with Action_found intent and receive messages when searching for each device. For each device, the system broadcasts Action_found Intent, the Intent carrying field information Extra_device and Extra_class, Contains a bluetoothdevice and a bluetoothclass.

The following example shows how to register and process a broadcast that is issued after a device is discovered:

The code is as follows:

 1 2 3 4 5 6 7 8 9 
//Create a broadcastreceiver for action_found  private   final  broadcastreceiver Mreceiver =  New  broadcastreceiver () { public  voidonreceive, Intent Intent) {String action = intent.getaction ()//When Discovery finds a device  if  (bluetoothdevice.ac Tion_found.equals (Action)) {//Get the Bluetoothdevice object from the Intent bluetoothdevice device = INTENT.G Etparcelableextra (bluetoothdevice.extra_device 

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.