Today I learned the basics of Android Bluetooth, including the operation to turn Bluetooth on and off, and the data transfer between two phones via Bluetooth. Here's a look at the code:
first, you need to Add the rights to the Bluetooth operation in the manifest file:
<uses-permission android:name= "Android.permission.BLUETOOTH"/><uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>
There are two ways to turn on Bluetooth:
The first type: Intent Intent = new Intent (bluetoothadapter. Action_request_enable);
Startactivityforresult (intent,1);
This way the user is prompted whether to turn on Bluetooth
The second type:bluetoothadapter. Enable ();
This way the system directly turns on Bluetooth
Operation to turn off Bluetooth:bluetoothadapter. disable ();
Search for basic operations for nearby Bluetooth:
1.BluetoothAdapter Bluetoothadapter = Bluetoothadapter.getdefaultadapter (); //Get the default Bluetooth adapter
2. if (bluetoothadapter. isdiscovering ()) {//If the search is exact, first cancel the search
bluetoothadapter. Canceldiscovery ();
}
bluetoothadapter. StartDiscovery ();
In the second part of the search, a broadcast bluetoothdevice will be issued. Action_found
3. Create and register broadcastreceiver and perform the operation in the onreceive method , the key code is as follows:
@Overridepublic void OnReceive (Context arg0, Intent arg1) {//TODO auto-generated method stubstring action = Arg1.getactio n ();//Get a Bluetooth device that has been searched if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {Bluetoothdevice device = Arg1.getparcelableextra (Bluetoothdevice.extra_device);//the device being searched for is not an already bound device if (device.getbondstate ()! = bluetoothdevice.bond_bonded) {//The new Bluetooth device and name to be searched is displayed in TextView show.append (device.getname () + ":" +device.getaddress () + " \ n ");}} else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {// Description The search has completed setprogressbarindeterminatevisibility (false); Settitle ("Search for Bluetooth Device");}}
2. Communication between two Bluetooth devices
Add the rights to the Bluetooth operation in the manifest file:
<uses-permission android:name= "Android.permission.BLUETOOTH"/><uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>
A. transmission of data between Bluetooth on two phones is achieved via bluetoothsocket and Bluetoothserversocket
B. Ways to create Bluetoothsocket and Bluetoothserversocket are as follows:
Clientsocket = Device
. Createrfcommsockettoservicerecord (My_uuid);
ServerSocket = Bluetoothadapter
. Listenusingrfcommwithservicerecord (NAME, My_uuid);
It is important to note that:
UUID my_uuid = UUID
. FromString ("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c");
The 5dd231bf-d217-4e85-a26c-5e5cfda9aa0c is a system-supplied UUID. Randomuuid (). toString (); the generated can be used for transmitting ID between Bluetooth devices, this is the only
Name is a string, which we give freely.
B. create a thread class that accepts data:
Private class Acceptthread extends Thread{private bluetoothserversocket serversocket;private bluetoothsocket socket; Private InputStream is;private outputstream os;public acceptthread () {//Create Bluetoothserversocket object try {serverSocket = Bluetoothadapter.listenusinginsecurerfcommwithservicerecord ("Name", Uuid.fromstring (" 5dd231bf-d217-4e85-a26c-5e5cfda9aa0c "));} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic void Run () {//TODO auto-generated method stub//wait to accept the Bluetooth client's request try {socket = serversocket.accept (); is = Socke T.getinputstream (); OS = Socket.getoutputstream (); while (true) {byte[] buffer = new Byte[128];int count = is.read (buffer); Message message = new Message (); message.obj = new String (buffer,0, Count, "Utf-8"); handler.sendmessage (message);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Get a Bluetooth device that is already bound and display it with a list
Luetoothadapter bluetoothadapter = Bluetoothadapter.getdefaultadapter ();//Get the default Bluetooth adapter c.set<bluetoothdevice> Pairedevices = Bluetoothadapter.getbondeddevices ();//Get the Bluetooth device already bound if (pairedevices.size () > 0) {//If there is a string []data = New String[pairedevices.size ()];for (Bluetoothdevice bluetoothdevice:pairedevices) {data[count++] = Bluetoothdevice.getname () + ":" +bluetoothdevice.getaddress ();//Get the name and address of the Bluetooth device that is bound}adapter = new arrayadapter<string > (mainactivity.this,android. R.layout.simple_expandable_list_item_1,data); List.setadapter (adapter);
To bind the listener events for each list item in lists:
list.setonitemclicklistener (new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> Parent, view view, int Position,long ID) {//TODO auto-generated method stubstring s = ad Apter.getitem (position);//Get the address of the Bluetooth device you want to connect to, String = S.substring (S.indexof (":") +1). Trim (); if (null = = device) {// Acquiring a Bluetooth device, equivalent to the Socketip address set by the network client, device = Bluetoothadapter.getremotedevice (address);} if (null = = Clientsocket) {try {clientsocket = Device.createinsecurerfcommsockettoservicerecord (Uuid.fromstring (" 5dd231bf-d217-4e85-a26c-5e5cfda9aa0c "));//Start connecting Bluetooth device Clientsocket.connect (); OS = Clientsocket.getoutputstream ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} if (null! = OS) {//Send a string to server side try {os.write ("This is data sent over by another phone". GetBytes ("Utf-8")); Toast.maketext (Mainactivity.this, "Send Success", 1000);} catch (Exception e) {//TODO auto-generated catch Blocktoast.maketext (Mainactivity.this, "Send Failed", 1000); E.printstacktrace ();} }} }} );
Deploy the app to two phones, respectively, for Bluetooth communication. Note that this method only supports simple data transmission, if you need to book binary files, such as audio, or not.
SOURCE download
Android transmits data via Bluetooth for two phones