Wednesday, February 19, 2014

Android Bluetooth Development Analysis


be due to the recent development of a block of data is being transmitted via Bluetooth, in reference to the relevant information, and read the official documentation of Android, the Android summarized in Bluetooth module used.

1. use the response permission Bluetooth
  



2. configure the local Bluetooth module
Here we must first understand the operation of a core class for Bluetooth BluetoothAdapter
 
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter ();
/ / Directly open the Bluetooth system settings panel
Intent intent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult (intent, 0x1);
/ / Directly open the Bluetooth
adapter.enable ();
/ / Turn off Bluetooth
adapter.disable ();
/ / Open the local Bluetooth discovery (turned on by default 120 seconds, the time can be extended to a maximum of 300 seconds)
Intent discoveryIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300) ;/ / set the duration (maximum 300 seconds)


3 search for Bluetooth devices
.Use BluetoothAdapter of startDiscovery () method to search for Bluetooth devices
startDiscovery () method is an asynchronous method returns immediately after the call. This method will search for other Bluetooth devices, the process will continue for 12 seconds. After this method is called, the search process is actually carried out in a System Service, so you can call cancelDiscovery () method to stop the search (which can be called when not running discovery request).
After the request Discovery, the system starts to search for Bluetooth devices, in this process, the system will send three broadcast:
ACTION_DISCOVERY_START: Start Search
ACTION_DISCOVERY_FINISHED: Search ends
ACTION_FOUND: find the device, the Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, contain BluetooDevice and BluetoothClass.
We can register their corresponding responses BroadcastReceiver to receive broadcasts in order to achieve certain functionality
 
/ / Create a broadcast receiver ACTION_FOUND BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver () {
public void onReceive (Context context, Intent intent) {
String action = intent.getAction ();
/ / Find the device
if (BluetoothDevice.ACTION_FOUND.equals (action)) {
/ / Get the device object from the Intent
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
/ / The name and address of the device into the array adapter, for display in the ListView
mArrayAdapter.add (device.getName () + "\ n" + device.getAddress ());
}
}
};
/ / Register BroadcastReceiver
IntentFilter filter = new IntentFilter (BluetoothDevice.ACTION_FOUND);
After unbinding
/ / Do not forget; registerReceiver (mReceiver, filter)



4. Bluetooth Socket Communication
If you intend to propose a connection between two Bluetooth devices, the mechanism for the server and the client must implement. When two devices owned BluetoothSocket a connection in the same RFCOMM channel, two devices can be said to establish a connection.
Ways server device and a client device to get BluetoothSocket is different. Is accepted by the server device to obtain an incoming connection, and the client device is by opening an RFCOMM channel to the server to get the.


server implementations
To get BluetoothServerSocket by calling BluetoothAdapter of listenUsingRfcommWithServiceRecord (String, UUID) method (UUID for pairing between the client and server side of)
Call BluetoothServerSocket the accept () method listens for connection requests, if the request is received, it returns a BluetoothSocket instance (this method is block method, should be placed in a new thread)
If you do not want to accept other connections, the call BluetoothServerSocket the close () method to release resources (After calling this method, BluetoothSocket instance before and did not get close. However, due to a moment RFCOMM allows only one connection at a channel, then the general After accept a connection, then close out BluetoothServerSocket)
 
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) {}
}
}



client implementations
Get BluetoothService
server by searchingCall BluetoothService of listenUsingRfcommWithServiceRecord (String, UUID) method to get BluetoothSocket (the UUID should be the same as the server UUID)
Call BluetoothSocket the connect () method (which is a block method), if the UUID UUID match with the server, and the server connection is accept, then the connect () method returns
Note: Before calling connect () method should be determined not currently searching for devices, otherwise the connection will become very slow and prone to failure
 
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread (BluetoothDevice device) {
/ / Use a temporary object that is later assigned to mmSocket,
/ / Because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;

/ / Get a BluetoothSocket to connect with the given BluetoothDevice
try {
/ / MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord (MY_UUID);
} Catch (IOException e) {}
mmSocket = tmp;
}

public void run () {
/ / Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery ();

try {
/ / Connect the device through the socket. This will block
/ / Until it succeeds or throws an exception
mmSocket.connect ();
} Catch (IOException connectException) {
/ / Unable to connect; close the socket and get out
try {
mmSocket.close ();
} Catch (IOException closeException) {}
return;
}

/ / Do work to manage the connection (in a separate thread)
manageConnectedSocket (mmSocket);
}

/ ** Will cancel an in-progress connection, and close the socket * /
public void cancel () {
try {
mmSocket.close ();
} Catch (IOException e) {}
}
}




4. connection management (Data Communications)
Respectively, through BluetoothSocket the getInputStream () and getOutputStream () method to get the InputStream and OutputStream
Use read (bytes []) and write (bytes []) method to read and write operations are
Note: read (bytes []) method will always block, known to the information read from the stream, and write (bytes []) method is not often the block (for example, in another device did not read or intermediate buffer is full Under the circumstances, write method will block)
 
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) {}
}
}




citations: Android official SDK, "Android / OPhone fully developed handouts"
I blog Original Address: http://blog.csdn.net/gd920129/article/details/ 7487761 <-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
The reply was deleted at 2012-04-27 14:08:59 moderator

Reply:
Learn good ~ ~ ~
Reply:
Learn
Reply:
Learn ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・
Reply:
The landlord wrote very seriously ah, just watching the document typesetting know
Reply:
Yes, the first collection, use and we'll see
Reply:
Learn bocai234.com

Reply:
Thank learning
Reply:
Learn 3Q
Reply:
Learning, thank you
Reply:
Favorite look good
Reply:
Yes, the first collection, use and we'll see
Reply:
The reply was deleted at 2012-04-27 19:24:05 moderator

Reply:
Thank for sharing, collection next!
Reply:
Thank for sharing, collection next!
Reply:
Collectors
Reply:
The reply was deleted at 2012-04-28 08:22:47 moderator

Reply:
Study, the first to accept
Reply:
The reply was deleted at 2012-04-28 09:03:31 moderator

Reply:
The reply was deleted at 2012-04-28 09:04:10 moderator

Reply:
references, 5th Floor reply:
landlord write very seriously ah, just looking at the document's layout to know

Thank you ~
These days are trying to write a Bluetooth communication module, to the time and then released the source code to share ~
Reply:
Yes, the first collection, use and we'll see
Reply:
After learning of the ..
Reply:
The reply was deleted at 2012-04-28 09:26:46 moderator

Reply:
Landlord wishers
Reply:
Support a
Reply:
Yes, really good
Reply:
The reply was deleted at 2012-04-28 09:47:12 moderator

Reply:
Thanks for sharing!
Reply:
Thanks for sharing!
Reply:

Reply:
The reply was deleted at 2012-04-28 15:55:02 moderator

Reply:
The reply was deleted at 2012-04-28 11:00:03 moderator

Reply:
The reply was deleted at 2012-04-28 11:14:01 moderator

Reply:
Little meaning
Reply:
Can I say? Such technology is very good! Thank you to share Oh! !
Reply:
The reply was deleted at 2012-04-28 14:34:32 moderator

Reply:
study!
Reply:
The reply was deleted at 2012-04-28 16:26:20 moderator

Reply:
I do not know the future trend is Android or Iphone. I wanted to learn to move programmed.
Reply:
Programming is complicated, but it should not be a mainstream Bluetooth, WIFI transmission should look. Landlord Come
Reply:
Much worse
Reply:
Yes, from the collection
Reply:
Expressed do not understand

Reply:
great!
Reply:
The reply was deleted at the moderator 2012-04-30 09:57:55

Reply:
The reply was deleted at the moderator 2012-04-30 09:00:30

Reply:
The reply was deleted at the moderator 2012-04-30 10:45:03

Reply:
The reply was deleted at the moderator 2012-04-30 10:45:03

Reply:
The reply was deleted at the moderator 2012-04-30 10:43:23

No comments:

Post a Comment