Java android bluetooth socket

How to create a bluetooth server socket in android?

I am trying to create a server program that just starts bluetooth, creates a server socket, waits for some device to connect and accepts the connection. The onClick() method starts the bluetooth, then I call the AcceptThread() method to create a server socket and start listening. Then run() is called which accepts a connection. But it is not working. My app just stops. Any idea why? The code is given below:

public class MainActivity extends Activity < public BluetoothAdapter mBluetoothAdapter; private BluetoothServerSocket mmServerSocket; private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); TextView text; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.textView1); >@Override public boolean onCreateOptionsMenu(Menu menu) < getMenuInflater().inflate(R.menu.main, menu); return true; >public void onClick(View view) < switch (view.getId()) < case R.id.button1: mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) < text.setText("Does not support bluetooth"); return; >Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); text.setText("Discoverable!!"); AcceptThread(); run(); > > public void changeT(String str) < text.setText(str); >public void AcceptThread() < BluetoothServerSocket tmp = null; try < tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("MYYAPP", MY_UUID_SECURE); >catch (IOException e) < >mmServerSocket = tmp; > public void run() < BluetoothSocket socket = null; while (true) < try < socket = mmServerSocket.accept(); changeT("listening"); >catch (IOException e) < break; >if (socket != null) < changeT("doneeeee"); try < mmServerSocket.close(); >catch (IOException e) < e.printStackTrace(); >break; > > > > 

1 Answer 1

The problem was the AcceptThread() and run() functions were running before the adapter could be turned on. A single line before the AcceptThread() solved this.

Also, run() has to be run in a different thread.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.13.43530

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

Читайте также:  8bitdo sn30 pro bluetooth

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.

Источник

BluetoothSocket

The interface for Bluetooth Sockets is similar to that of TCP sockets: Socket and 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() . 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 InputStream and 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 BLUETOOTH permission.

Developer Guides

For more information about using Bluetooth, read the Bluetooth developer guide.

See Also

Источник

Android example source code file (BluetoothServerSocket.java)

This example Android source code file (BluetoothServerSocket.java) is included in the DevDaily.com «Java Source Code Warehouse» project. The intent of this project is to help you «Learn Android by Example» TM .

Java — Android tags/keywords

android, bluetoothserversocket, bluetoothsocket, closeable, handler, io, ioexception, os

The BluetoothServerSocket.java Android example source code

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.bluetooth; import android.os.Handler; import java.io.Closeable; import java.io.IOException; /** * A listening Bluetooth socket. * * 

The interface for Bluetooth Sockets is similar to that of TCP sockets: * and . On the server * side, use a to create a listening server * socket. When a connection is accepted by the , * it will return a new to manage the connection. * On the client side, use a single to both intiate * 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 listenting that's ready for * incoming connections, use * . Then call * to listen for incoming connection requests. This call * will block until a connection is established, at which point, it will return * a to manage the connection. Once the is acquired, it's a good idea to call on * the when it's no longer needed for accepting * connections. Closing the will not * close the returned . * *

is thread * safe. In particular, will always immediately abort ongoing * operations and close the server socket. * *

Note: * Requires the permission. * * */ public final class BluetoothServerSocket implements Closeable < /*package*/ final BluetoothSocket mSocket; private Handler mHandler; private int mMessage; /** * Construct a socket for incoming connections. * @param type type of socket * @param auth require the remote device to be authenticated * @param encrypt require the connection to be encrypted * @param port remote port * @throws IOException On error, for example Bluetooth not available, or * insufficient priveleges */ /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port) throws IOException < mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null); >/** * Block until a connection is established. *

Returns a connected on successful connection. *

Once this call returns, it can be called again to accept subsequent * incoming connections. *

can be used to abort this call from another thread. * @return a connected * @throws IOException on error, for example this call was aborted, or * timeout */ public BluetoothSocket accept() throws IOException < return accept(-1); >/** * Block until a connection is established, with timeout. *

Returns a connected on successful connection. *

Once this call returns, it can be called again to accept subsequent * incoming connections. *

can be used to abort this call from another thread. * @return a connected * @throws IOException on error, for example this call was aborted, or * timeout */ public BluetoothSocket accept(int timeout) throws IOException < return mSocket.accept(timeout); >/** * Immediately close this socket, and release all associated resources. *

Causes blocked calls on this socket in other threads to immediately * throw an IOException. *

Closing the will not * close any received from . */ public void close() throws IOException < synchronized (this) < if (mHandler != null) < mHandler.obtainMessage(mMessage).sendToTarget(); >> mSocket.close(); > /*package*/ synchronized void setCloseHandler(Handler handler, int message) < mHandler = handler; mMessage = message; >>

Other Android examples (source code examples)

Here is a short list of links related to this Android BluetoothServerSocket.java source code file:

Источник

Оцените статью
Adblock
detector