Bluetooth socket connection
I’m creating an application that uses an android to send and receive data via bluetooth. but I’m having problems when creating the socket. He gets caught in that line mmSocket btserver.accept = (); And I can not pair with any device. I have another doubt, I can make that communication with an android and a symbian?
1 Answer 1
The code is below. He finds devices but does not open the communication socket.
public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); bluetooth = BluetoothAdapter.getDefaultAdapter(); msg = (TextView) findViewById(R.id.msg); if (bluetooth.isEnabled()) < String address = bluetooth.getAddress(); String name = bluetooth.getName(); toastText = name + " : " + address; >else toastText = "Bluetooth is not enabled"; Toast.makeText(this, toastText, Toast.LENGTH_LONG).show(); msg.append("Bluetooth is not enabled"); enableBT = BluetoothAdapter.ACTION_REQUEST_ENABLE; startActivityForResult(new Intent(enableBT), 0); String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE; startActivityForResult(new Intent(aDiscoverable),DISCOVERY_REQUEST); registerReceiver(new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String prevScanMode = BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE; String scanMode = BluetoothAdapter.EXTRA_SCAN_MODE; int scanMode1 = intent.getIntExtra(scanMode, -1); int prevMode1 = intent.getIntExtra(prevScanMode, -1); >>, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)); BroadcastReceiver discoveryResult = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName, Toast.LENGTH_SHORT).show(); msg.append("\n"+remoteDeviceName); msg.append("\n"+remoteDevice); >>; BroadcastReceiver discoveryMonitor = new BroadcastReceiver() < String dStarted = BluetoothAdapter.ACTION_DISCOVERY_STARTED; String dFinished = BluetoothAdapter.ACTION_DISCOVERY_FINISHED; public void onReceive(Context context, Intent intent) < if (dStarted.equals(intent.getAction())) < Toast.makeText(getApplicationContext(), "Discovery Started . . . ", Toast.LENGTH_SHORT).show(); >else if (dFinished.equals(intent.getAction())) < Toast.makeText(getApplicationContext(), "Discovery Completed . . . ", Toast.LENGTH_SHORT).show(); >> >; registerReceiver(discoveryMonitor, new IntentFilter(dStarted)); registerReceiver(discoveryMonitor, new IntentFilter(dFinished)); startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), DISCOVERY_REQUEST); try < btserver = bluetooth.listenUsingRfcommWithServiceRecord(name, uuid); >catch (IOException e1) < e1.printStackTrace(); >Thread acceptThread = new Thread(new Runnable() < public void run() < try < btserver.accept(); >catch (IOException e) < Log.d("BLUETOOTH", e.getMessage()); >> >); acceptThread.start(); > > >
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.
Connect to Android Bluetooth socket
Hi I am trying to create an Android app which will connect to a Blue SMiRF Bluetooth dongle which I want to send data to. I have read over the developer pages and looked at multiple different examples however I am currently having trouble creating a connection to the socket. The Bluetooth portion of the code is pretty much from an example that I was able to find. When trying to connect to the Bluetooth dongle the app gets a force close because there is some error I am not handling correctly. However I have also tried to use the app just to connect to another PC and the connection wont get established correctly for some reason even though I am already paired with the device through the Bluetooth settings before I even run the app. I have posted some of the more important code below for where I think my issue may be. Any help will be very appreciated, please let me know if I should post any additional code.
protected void connect(BluetoothDevice device) < //BluetoothSocket socket = null; try < //Create a Socket connection: need the server's UUID number of registered socket = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); socket.connect(); Log.d("EF-BTBee", ">>Client connectted"); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[] < (byte) 0xa0, 0, 7, 16, 0, 4, 0 >); new Thread() < public void run() < while(true) < try < Log.d("EF-BTBee", ">>Send data thread!"); OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[] < (byte) 0xa2, 0, 7, 16, 0, 4, 0 >); > catch (IOException e) < Log.e("EF-BTBee", "", e); >> >; >.start(); > catch (IOException e) < Log.e("EF-BTBee", "", e); >finally < if (socket != null) < try < Log.d("EF-BTBee", ">>Client Close"); socket.close(); finish(); return ; > catch (IOException e) < Log.e("EF-BTBee", "", e); >> > >`
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] ); socket = (BluetoothSocket) m.invoke(device, 1);
Thanks for the comment. Unfortunately still having no luck with it creating the Bluetooth socket connection correctly.
Having reread it (must have read it wrong initially), but is able to create the Bluetooth socket correctly, still having a problem having it actually connect.