Android bluetooth to bluetooth connection

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(); >>); > >

  • 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.

Источник

Connecting to a specific bluetooth port on a bluetooth device using Android

Is there any way for Android to connect to a Bluetooth device using a specific port instead of using service UUID? I know this option is available in other platforms which provide Bluetooth support (Java ME for example by specifying a «btspp://» style URL). Thanks!

3 Answers 3

Ok, it’s been a while, but I found a solution to the problem. I actually intended to give up and use UUID, but I kept getting a Service Discovery Failed (IO)exception, and when I tried to find a solution to the service discovery issue, I found the solution to my original question. Ain’t life something?:)

Anyways, this is the link I stumbled upon, though you should note there is a mistake in the answer (they actually simply connected to port 1, instead of using a service UUID).

And after this short history lesson, here is the solution:

Using reflection, it is possible to create the Rfcomm socket connecting to a port number instead of UUID:

int bt_port_to_connect = 5; // just an example, could be any port number you wish BluetoothDevice device = . ; // get the bluetooth device (e.g., using bt discovery) BluetoothSocket deviceSocket = null; . // IMPORTANT: we create a reference to the 'createInsecureRfcommSocket' method // and not(!) to the 'createInsecureRfcommSocketToServiceRecord' (which is what the // android SDK documentation publishes Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] ); deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect); 
  1. since we’re using Invoke, the first parameter is the object we’re invoking the method on, the second parameter of invoke is actually the first function parameter)
  2. There is also a secure version available (‘createRfcommSocket’), which accepts a bluetooth channel number as a single parameter (again, since this is invoke style, you’ll need to pass the object to invoke the method on, as mentioned in -1- )
  3. I found what appears to be a link to these functions’ prototypes

Источник

Programmatically connect to paired Bluetooth device

Is there a way, using the Android SDK, to programmatically connect to an already-paired Bluetooth device? In other words: I can go into Settings -> Wireless & networks -> Bluetooth settings, and tap the device (listed as «Paired but not connected»), at which point it will connect. I’d like to be able to do this programmatically, but don’t see a way to do this. I see the options to create an RFCOMM socket, and for a SPP device, I’m assuming that’ll do the connection part as well, but for an A2DP device, where the actual data transfer will be handled by the OS rather than by my app, I think that’s not applicable?

4 Answers 4

Okay, since this was driving me crazy, I did some digging into the source code and I’ve found a 100% reliable (at least on my Nexus 4, Android 4.3) solution to connect to a paired A2DP device (such as a headset or Bluetooth audio device). I’ve published a fully working sample project (easily built with Android Studio) that you can find here on Github.

Essentially, what you need to do is:

  • Get an instance of the BluetoothAdapter
  • Using this instance, get a profile proxy for A2DP:

adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);

where listener is a ServiceListener that will receive a BluetoothProfile in its onServiceConnected() callback (which can be cast to a BluetoothA2dp instance)

Method connect = BluetoothA2dp.class.getDeclaredMethod(«connect», BluetoothDevice.class);

String deviceName = "My_Device_Name"; BluetoothDevice result = null; Set devices = adapter.getBondedDevices(); if (devices != null) < for (BluetoothDevice device : devices) < if (deviceName.equals(device.getName())) < result = device; break; >> > 

Which, at least for me, caused an immediate connection of the device.

Источник

Читайте также:  Bluetooth гарнитура baseus a01
Оцените статью
Adblock
detector