Bluetooth in Android

Source: Internet
Author: User

 

Basics:

 

This document describes how to use Android Bluetooth APIs to complete four main tasks of data exchange: Creating Bluetooth, finding available Bluetooth devices or matching Bluetooth devices in the local area, connecting devices, and transmitting data.

 

All Bluetooth APIs are under the android. bluetooth package. The following are the classes and interfaces required to create a Bluetooth connection:

 

Thadapter:

 

Indicates the local Bluetooth adapter. BluetoothAdapter is an access point for all Bluetooth switches. Using it, you can find other Bluetooth devices, find some matching devices, and instantiate a thdevice with a MAC address. Create a ipvthserversocket to listen to other devices and then communicate with them.

 

Effecthdevice:

 

Indicates a remote Bluetooth device. It is used to request a connection with a remote device through ipvthsocket. The latter queries the basic information of a device, such as name, address, class, or combined status.

 

BluetoothSocket:

 

Indicates a Bluetooth socket interface (similar to TCP socket ). It is a connection point. The running device exchanges data in the form of InputStream and OutputStream.

 

BluetoothServiceSocket:

 

Indicates an open service socket used to listen to received requests (similar to TCP server socket ). To connect to a device, a device must open a service socket. When a remote device requests a connection, when the connection is received, descrithservicesocket returns a descrithsocket.

 

BluetoothClass:

 

Describes the general features and performance of a bluetooth device. This is a series of read-only attributes. Defines the primary and minimum device categories and services. However, the device attributes and services it describes are not completely reliable, but they are useful when it represents the device type.

 

Descrithprofile:

 

An interface that represents the Bluetooth property. Wireless interface rules based on wireless bluetooth communication.

 

BluetoothHeadset:

 

Provides support for using Bluetooth headsets on mobile phones.

 

Export tha2dp:

 

Defines what data can be transmitted between bluetooth.

 

Export thprofiles. ServiceListener:

 

When the bluetooth device is connected or disconnected, use it to notify the BluetoothProfiles IPC client. It is an interface.

 

Bluetooth permission:

 

To use Bluetooth, you must declare the permission in your application.

 

<Manifest...>

<Uses-permission android: name = "android. permission. BLUETOOTH"/>

...

</Manifest>

 

Two permissions: BLUETOOTH and bluetooth admin.

 

When using bluetooth admin, you must declare BLUETOOTH.

 

Create Bluetooth:

 

1. Get javasthadaper.

 

Descrithadapter mBluetoothAdapter = descrithadapter. getdefaadapter adapter ();

If (mblustmthadapter = null ){

// Device does not support Bluetooth

}

 

If the parameter is not null, a bluetooth device is available on the local device.

 

2. Use Bluetooth.

 

If (mblustmthadapter. isEnabled ()){

Intent enableBtIntent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE );

StartActivityForResult (enableBtIntent, REQUEST_ENABLE_BT );

}

 

View matched devices:

 

Set <effecthdevice> repeated reddevices = mblustmthadapter. getBondedDevices ();

// If there are using red devices

If (repeated reddevices. size ()> 0 ){

// Loop through using red devices

For (incluthdevice device: inclureddevices ){

// Add the name and address to an array adapter to show in a ListView

MArrayAdapter. add (device. getName () + "\ n" + device. getAddress ());

}

}

 

Device found:

 

// 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 (descrithdevice. ACTION_FOUND.equals (action )){

// Get the specified thdevice object from the Intent

Effecthdevice device = intent. getParcelableExtra (effecthdevice. 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 (effecthdevice. ACTION_FOUND );

RegisterReceiver (mReceiver, filter); // Don't forget to unregister during onDestroy

 

Connection device:

 

As a service provider:

 

Public AcceptThread (){

// Use a temporary object that is later assigned to mmServerSocket,

// Because mmServerSocket is final

Descrithserversocket tmp = null;

Try {

// MY_UUID is the app's UUID string, also used by the client code

Tmp = mblustmthadapter. listenUsingRfcommWithServiceRecord (NAME, MY_UUID );

} Catch (IOException e ){}

MmServerSocket = tmp;

}

 

Public void run (){

Descrithsocket 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 ){}

}

}

 

As a client:

 

Private class ConnectThread extends Thread {

Private final ipvthsocket mmSocket;

Private final effecthdevice mmDevice;

 

Public ConnectThread (effecthdevice device ){

// Use a temporary object that is later assigned to mmSocket,

// Because mmSocket is final

Optional thsocket tmp = null;

MmDevice = device;

 

// Get a pair thsocket to connect with the given pair thdevice

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

Mblustmthadapter. 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 ){}

}

}

 

Manage connections:

 

Private class ConnectedThread extends Thread {

Private final ipvthsocket mmSocket;

Private final InputStream mmInStream;

Private final OutputStream mmOutStream;

 

Public ConnectedThread (Fig 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 ){}

}

}

From Yanyun's column

Related Article

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.