Android BluetoothSocket tutorial with examples
The interface for Bluetooth Sockets is similar to that of TCP sockets: java.net.Socket and java.net.ServerSocket.
On the server side, use a BluetoothServerSocket to create a listening server socket.
When a connection is accepted by the BluetoothServerSocket, it will return a new BluetoothSocket to manage the connection.
On the client side, use a single BluetoothSocket to both initiate an outgoing connection and to manage the connection.
The most common type of Bluetooth socket is RFCOMM, which is the type supported by the Android APIs.
RFCOMM is a connection-oriented, streaming transport over Bluetooth.
It is also known as the Serial Port Profile (SPP).
To create a BluetoothSocket for connecting to a known device, use *BluetoothDevice#createRfcommSocketToServiceRecord BluetoothDevice.createRfcommSocketToServiceRecord()*.
Then call #connect() to attempt a connection to the remote device.
This call will block until a connection is established or the connection fails.
To create a BluetoothSocket as a server (or «host»), see the BluetoothServerSocket documentation.
Once the socket is connected, whether initiated as a client or accepted as a server, open the IO streams by calling #getInputStream and #getOutputStream in order to retrieve java.io.InputStream and java.io.OutputStream objects, respectively, which are automatically connected to the socket.
BluetoothSocket is thread safe.
In particular, #close will always immediately abort ongoing operations and close the socket.
Note: Requires the *android.Manifest.permission#BLUETOOTH* permission.
Example
The following code shows how to use BluetoothSocket from android.bluetooth.
import java.util.UUID; import android.support.v7.app.ActionBarActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity < private static final UUID SERVICE_UUID = UUID.fromString("00001108-0000-1000-8000-00805F9B3000"); BluetoothDevice mDevice = null;// w w w. d e m o2 s . c o m @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (!btAdapter.equals(null)) < Log.d("pcall", "Bluetoothtesttest"); > else < Log.d("pcall", "Bluetoothtesttest"); finish(); > if (btAdapter.isEnabled()) < Log.d("pcall", "Bluetoothtesttestdemo"); for (BluetoothDevice dev : btAdapter.getBondedDevices()) < Log.d("pcall", "test " + dev.getName() + " " + dev.getAddress()); if (dev.getName().equals("PTM-ICN")) < mDevice = dev; break; > > > else < Log.d("pcall", "Bluetoothtesttesttest"); finish(); > > @Override public boolean onCreateOptionsMenu(Menu menu) < super.onCreateOptionsMenu(menu); menu.add(0, Menu.FIRST, Menu.NONE, "Call"); return true; > @Override public boolean onOptionsItemSelected(MenuItem item) < BluetoothSocket socket = null; if (mDevice != null) < try < socket = mDevice.createRfcommSocketToServiceRecord(SERVICE_UUID); Log.d("pcall", "Socket created"); socket.connect(); Log.d("pcall", "connected"); //InputStream in = socket.getInputStream(); //OutputStream out = socket.getOutputStream(); // . > catch (Exception e) < Log.d("pcall", e.getMessage()); > finally < if (socket != null) < try < socket.close(); >catch (Exception e) < >> > > return super.onOptionsItemSelected(item); > >
import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.ParcelUuid; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Set; public class MainActivity extends AppCompatActivity < private OutputStream outputStream; private InputStream inStream; @Override/*w w w . d e m o 2s . c o m */ protected void onCreate(Bundle savedInstanceState) < try < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.init(); > catch (Exception e) < this.showAlert(e.getMessage()); > > private void showAlert(String msg) < AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage(msg); alertDialog.show(); > private void init() throws IOException < Log.i("info", "init is run"); BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter(); Log.e("error", "Get adapter fine"); if (blueAdapter != null) < if (blueAdapter.isEnabled()) < Set bondedDevices = blueAdapter.getBondedDevices(); if (bondedDevices.size() > 0) < Object[] devices = (Object[]) bondedDevices.toArray(); for (Iterator i = bondedDevices.iterator(); i.hasNext();) < BluetoothDevice device = i.next(); String dName = device.getName(); if (device.getName() == "our_device_name") < ParcelUuid[] uuids = device.getUuids(); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); socket.connect(); this.outputStream = socket.getOutputStream(); this.inStream = socket.getInputStream(); return; > > > throw new RuntimeException("Can't find bluetooth device"); > else < Log.e("error", "Bluetooth is disabled."); > > else < Log.e("error", "Bluetooth is not available."); > > public void sendMsg(View view) < try < String direction = view.getTag().toString(); this.outputStream.write(direction.getBytes()); > catch (Exception e) < this.showAlert(e.getMessage()); > > >
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Set; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class TestingActivity extends Activity < private BluetoothAdapter bAdapter; private BluetoothDevice bDev; private UUID uid = UUID.fromString("bd302500-d594-11e0-9572-0800200c9a66"); public final static UUID uuid = UUID.fromString("00001101-0000-1000-8000-008099999999"); /** Called when the activity is first created. */ @Override// w w w . d e m o 2 s . c o m public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); Button enumerate = (Button) findViewById(R.id.enumerate); enumerate.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < TextView logarea = (TextView) findViewById(R.id.textlog); bAdapter = BluetoothAdapter.getDefaultAdapter(); Set bDevices = bAdapter.getBondedDevices(); Iterator i = bDevices.iterator(); BluetoothDevice chx; System.out.println("enumerating bt devices"); while (i.hasNext()) < chx = i.next(); System.out.println(chx.getName()); if (chx.getName().equals("CHX")) < System.out.println("Found CHX"); > bDev = chx; Button enumerate = (Button) findViewById(R.id.enumerate); enumerate.setText("Found CHX"); enumerate.setEnabled(false); > logarea.append(" " + bDev.getBondState()); try < logarea.append("trying to create socket2"); BluetoothSocket socket = bDev.createRfcommSocketToServiceRecord(uuid); logarea.append("socket created? trying to connect"); socket.connect(); logarea.append("connected?, getting OStrean,IStream and trying to send"); OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); os.write("AT RV".getBytes("US_ASCII")); logarea.append("done sent i guess, now waiting and reading"); Thread.sleep(1000); byte[] stringbuff = new byte[256]; int numbytesread = is.read(stringbuff); String msg = new String(stringbuff, 0, numbytesread, "US_ASCII"); logarea.append("received message:" + msg); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); logarea.append("CARP"); System.out.println("can't create RF Comm Socket"); > catch (InterruptedException e) < // TODO Auto-generated catch block e.printStackTrace(); logarea.append("CARP"); System.out.println("Interuppted"); > > >); Button exit = (Button) findViewById(R.id.exit); exit.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < finish(); >>); > >
Related
- Android BluetoothSocket getOutputStream()
- Android BluetoothSocket getRemoteDevice()
- Android BluetoothSocket isConnected()
- Android BluetoothSocket tutorial with examples
- Android BluetoothSocket TYPE_RFCOMM
- Android android.bluetooth.le AdvertiseCallback
- Android AdvertiseCallback ADVERTISE_FAILED_ALREADY_STARTED
demo2s.com | Email: | Demo Source and Support. All rights reserved.