Android Bluetooth connection to send and receive data (excluding BLE)

Source: Internet
Author: User

The knowledge about Android Bluetooth has been skipped. You can search for it in hundreds of times.

This code has been verified by the project and is completely OK

Directly go to the Code step:

Private descrithadapter adapter;

1. // obtain the Bluetooth adapter

Adapter = descrithadapter. getdefaadapter adapter ();

// Enable Bluetooth
If (! Adapter. isEnabled ()){
// The pop-up dialog box prompts you to select whether to enable Bluetooth
Intent intent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE );
StartActivityForResult (intent, 0 );
// Or enable it without prompting
// BAdapter. enable ();
}

2. Get Bluetooth MacAddress

// Search for and obtain the paired Bluetooth
NameAddress = getmediareddevice (adapter); // Add a definition for the variable

// Obtain the name list and address list
If (nameAddress. size ()> 0 ){
BlueNames = nameAddress. get (0 );
BlueAddress = nameAddress. get (1 );
}

// Obtain the method. Here, I store the name and address in the set separately. To facilitate display in the ListView and other purposes, you can return the address as needed or only.

Private ArrayList <String> getmediareddevice (descrithadapter adapter ){
ArrayList <String> nameAndAddress = new ArrayList <String> ();
// Optional reddevicenames = new ArrayList <String> ();
Optional reddeviceaddress = new ArrayList <String> ();
Set <shortthdevice> repeated reddevices = adapter. getBondedDevices ();
If (repeated reddevices. size ()> 0 ){
// Parse them one by one
For (incluthdevice devices: inclureddevices ){
// Put it into the set
PairedDeviceNames. add (devices. getName () + "\ n"
+ Devices. getAddress ());
PairedDeviceAddress. add (devices. getAddress ());
}
// Save information
NameAndAddress. add (pairedDeviceNames );
NameAndAddress. add (pairedDeviceAddress );
}
Return nameAndAddress;
}

3. Connect to the bluetooth device through Address

// Connect the device
Device = adapter. getRemoteDevice (address );
Connect (device );

Public synchronized void connect (effecthdevice device ){

ConnectThread = new ConnectThread (device, this, adapter, handler, handlerUpdate );
ConnectThread. start ();
}

4. connect to a Bluetooth thread

Public class ConnectThread extends Thread {

// The variable is omitted here

Public ConnectThread (effecthdevice device, effecthadapter mAdapterr ){
This. mAdapter = mAdapter;
Int sdk = Build. VERSION. SDK_INT;
If (sdk> = 10 ){
Try {
MySocket = device
. CreateInsecureRfcommSocketToServiceRecord (MY_UUID );
} Catch (IOException e ){
E. printStackTrace ();
}
} Else {
Try {
MySocket = device. createRfcommSocketToServiceRecord (MY_UUID );
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}

}

Public void run (){
//
MAdapter. cancelDiscovery ();
Try {
MySocket. connect ();
// Start receiving data sent from a remote device
ConnectBluetooth = new ReceiveDatas (mySocket, receiveHandler );
ConnectBluetooth. start ();
// Output stream
MmOutStream = mySocket. getOutputStream ();
} Catch (IOException e ){
// TODO Auto-generated catch block

Try {
MySocket. close ();
} Catch (IOException ee ){
// TODO Auto-generated catch block
Ee. printStackTrace ();
}

}

}

// Write data
/* Call this from the main Activity to send data to the remote device */
Public void sendMessage (String msg ){
Byte [] buffer = new byte [16];
Try {
If (mmOutStream = null ){
Log. I ("info", "the output stream is empty ");
Return;
}
// Write data
Buffer = msg. getBytes ();
MmOutStream. write (buffer );
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Finally {
Try {
If (mmOutStream! = Null ){
MmOutStream. flush ();
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}

}

5. Read data

Public class ReceiveDatas extends Thread {
// The variable is skipped.

// Constructor
Public ReceiveDatas (javasthsocket socket ){

This. mmSocket = socket;
InputStream tempIn = null;

// Obtain the input stream
Try {
TempIn = socket. getInputStream ();
} Catch (IOException e ){
// TODO Auto-generated catch block
}
MmInStream = tempIn;
}

@ Override
Public void run (){
Byte [] buffer = new byte [1024]; // buffered data stream
Int bytes; // return the data read.
// Listen to the input stream
While (true ){
Try {
Bytes = mmInStream. read (buffer );
// Process data here ......


} Else {
Log. I ("info", "exception ");
}
} Catch (IOException e ){
Try {
If (mmInStream! = Null ){
MmInStream. close ();
}
Log. I ("info", "exception ");
Break;
} Catch (IOException e1 ){
// TODO Auto-generated catch block
E1.printStackTrace ();
}
}
Try {
Thread. sleep (50); // Delay
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}

 

 

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.