How to connect a bluetooth with desktop and android phone. i able to parring and connect bluetooth but unable to connected with Mouse, keyboard & pen device type.
Below given are both mobile device. but A50 device connect using other app and i want to connect M30s as mouse, keyboard.
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
btAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Hope this helps
App in Playstore
SourceCode in Github
Nothing to post here as code is in github
Its in kotlin ,convert to java using androidstudio
These one below are java but lacks/misses readme
1
2
3
Related
I have an app that runs 3 threads at the same time. One thread is for stablishing a bluetooth connection between the phone and another bluetooth device (Arduino). Thread 2 plays audio incoming from another phone via bluetooh. Thread 3 records and sends audio to the other phone via bluetooth.
The audio communication works with lots of glitches if phone is trying to stablish a connection with the Arduino (when thread 1 is running bluetoothsocket.connect();). However, when phone does not try to stablish a connection with the Arduino or the connection is already stablished and thread 1 is done, then the communication is good.
Here is the code for thread 1 - arduino (this code is with a class)
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// As mmSocket is final, we use a temporary socket variable
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
// Send the name of the disconnected device back to the UI Activity
sendDeviceConnectionToActivity(deviceMAC, false);
Log.d("Bluetoot connected -->", "NNNNNNNN" + connectException);
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket, mmDevice);
// mConnectedThread = new ConnectedThread(mmSocket);
// mConnectedThread.start();
Log.d("Bluetoot connected -->", mmDevice.getName());
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
the code for audio in thread 2 and 3 (this code is with a another class)
public void audioCreate() {
// Audio track object
track = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
16000, AudioFormat.CHANNEL_OUT_MONO,
encoding, minSize, AudioTrack.MODE_STREAM);
// Audio record object
recorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, 16000,
AudioFormat.CHANNEL_IN_MONO, encoding,
bufferSize);
}
public void initiateBluetoothConexion(BluetoothDevice deviceSelected) {
// Toast.makeText(getApplicationContext(), "Service On", Toast.LENGTH_SHORT).show();
deviceMAC = deviceSelected.getAddress();
mBluetoothAdapter.cancelDiscovery();
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
mConnectThread = new ConnectThread(deviceSelected);
mConnectThread.setPriority(10);
mConnectThread.start();
}
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// As mmSocket is final, we use a temporary socket variable
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
// Send the name of the disconnected device back to the UI Activity
sendDeviceConnectionToActivity(deviceMAC, false);
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket, mmDevice);
// mConnectedThread = new ConnectedThread(mmSocket);
// mConnectedThread.start();
Log.d("Bluetoot connected -->", mmDevice.getName());
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void manageConnectedSocket(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
// Cancel the thread that completed the connection
// if (mConnectThread != null) {
// mConnectThread.cancel();
// mConnectThread = null;
// }
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.setPriority(10);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Log.d(TAG, "Connected to " + mmDevice.getName());
sendDeviceConnectionToActivity(mmDevice.getAddress(), true);
// setState(STATE_CONNECTED);
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte buffer[] = null;
private byte playBuffer[] = null;
private boolean intercomm = false;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
intercomm = true;
}
public void run() {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
playBuffer = new byte[minSize];
// Playback received audio
track.play();
startRecording();
// receive recording until an exception occurs.
while (intercomm) {
try {
if (mmInStream.available() == 0) {
//Do nothing
} else {
mmInStream.read(playBuffer);
track.write(playBuffer, 0, playBuffer.length);
}
} catch (IOException e) {
Log.d("AUDIO", "Error when receiving recording");
sendDeviceConnectionToActivity(deviceMAC, false);
break;
}
}
}
// Record Audio
public void startRecording() {
Log.d("AUDIO", "Assigning recorder");
buffer = new byte[bufferSize];
// Start Recording
recorder.startRecording();
Log.d("startRecording", "passed");
// Start a thread
recordingThread = new Thread(new Runnable() {
#Override
public void run() {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
Log.d("startRecording", "sendRecording");
sendRecording();
}
}, "AudioRecorder Thread");
recordingThread.setPriority(10);
recordingThread.start();
}
// Method for sending Audio
public void sendRecording() {
// Infinite loop until microphone button is released
while (intercomm) {
try {
recorder.read(buffer, 0, bufferSize);
mmOutStream.write(buffer);
} catch (IOException e) {
Log.d("AUDIO", "Error when sending recording");
sendErrorsToActivity("Error sending audio");
}
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
intercomm = false;
stopPlaying();
stopRecording();
destroyProcesses();
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
// Stop playing and free up resources
public void stopPlaying() {
if (track != null) {
track.stop();
track.flush();
}
}
// Stop Recording and free up resources
public void stopRecording() {
if (recorder != null) {
recorder.stop();
}
}
public void destroyProcesses() {
//Release resources for audio objects
track.release();
recorder.release();
}
}
I tested the code in an octacore android oreo. However, when I did it in an phone sdk 23, it was worst.
Your AudioTrack is starving because it is not receiving data quickly enough from the arduino. This is most likely due to increased network contention during the BT connection process.
You appear to be configuring your AudioTrack with the smallest possible play-buffer. On most devices, this is only a few ms of audio, so if the AudioTrack isn't fed more data every few ms, it will starve, and you will hear a glitch.
One solution is to increase the AudioTrack's buffer size (perhaps to around 8000 samples or more).
In addition, you have not checked the return value from mmInStream.read(), which means you may be trying to "play" a playBuffer that is only partially filled.
Altering the thread priorities, as you are, is unlikely to make a qualitative difference.
I am in an Android project which uses Bluetooth sockets. The app is the client socket. But the app crashes when working. Can anyone help me in solving the issue.
here is the code
public class READ extends AppCompatActivity {
private static String btAdress = "00:10:60:D1:95:CD";
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
BluetoothAdapter btAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
}
public void ConnectThread(View v){
BluetoothDevice device;
device = btAdapter.getRemoteDevice(btAdress);
ConnectT(device);
}
public void ConnectT(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
mmDevice = device;
BluetoothSocket tmp = null;
String uuid = "a60f35f0-b93a-11de-8a39-08002009c666";
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (IOException e) { }
mmSocket = tmp;
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException nullException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
}
}
}
Thanks in Advance.
I have problem with connecting blutooth RfComm. I was able to connect to bluetooth and communicate but sometimes it doesn't connect. I am using standard uuid-00001101-0000-1000-8000-00805F9B34FB
please help me out :)
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
private ConnectThread(BluetoothDevice device) {
Log.d(TAG, "in ConnectThread");
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
Log.d(TAG, "createRfcommSocketToServiceRecord for " + mmDevice.getName());
// MY_UUID is the app's UUID string, also used by the server code
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
//tmp = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
Log.d(TAG, "in ConnectThread : run");
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
Log.d(TAG, "Try to Connect Socket");
// Connect the device through the socket. This will block
mmSocket.connect();
} catch (IOException connectException) {
try {
Log.i(TAG, "Trying fallback...");
mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1);
mmSocket.connect();
} catch (Exception e2) {
Log.e(TAG, "Couldn't establish Bluetooth connection!");
try {
mmSocket.close();
} catch (IOException e3) {
Log.e(TAG, "unable to close() socket during connection failure", e3);
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
}
// Will cancel an in-progress connection, and close the socket
private void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread implements Runnable {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "in ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.d(TAG, "in ConnectedThread : run");
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
//Log.d(TAG,"in ConnectedThread : run -- while");
try {
try {
sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
01-18 09:19:09.661 15692-16231/iconcreator.pidroid I/Main Activity :: Trying fallback...
01-18 09:19:09.661 2809-2873/? E/bt_btif_sock_rfcomm: find_rfc_slot_by_id unable to find RFCOMM slot id: 14
01-18 09:19:09.662 15692-16231/iconcreator.pidroid W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
01-18 09:19:09.743 16236-16236/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
01-18 09:19:09.846 2809-2859/? W/bt_rfcomm: port_rfc_closed RFCOMM connection in state 1 closed: Closed (res: 19)
01-18 09:19:09.846 15692-16231/iconcreator.pidroid E/Main Activity :: Couldn't establish Bluetooth connection!
01-18 09:19:09.847 2809-2873/? E/bt_btif_sock_rfcomm: find_rfc_slot_by_id unable to find RFCOMM slot id: 15
I've been create an app for Bluetooth control.
Everything is fine until I open BluetoothServerSocket to listen to an incoming connection.
here is my code:
public class ListeningThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public ListeningThread() {
BluetoothServerSocket temp = null;
try {
temp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);
Toast.makeText(getApplicationContext(), "Listening",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void run() {
BluetoothSocket bluetoothSocket;
// This will block while listening until a BluetoothSocket is returned
// or an exception occurs
while (true) {
try {
bluetoothSocket = bluetoothServerSocket.accept();
Toast.makeText(getApplicationContext(), "Alert", <-------//the code is not run through here, there is no toast coming out
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "A connection has been accepted.",
Toast.LENGTH_SHORT).show();
}
});
// Manage the connection in a separate thread
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
there is no error shown but when i triggered the ListeningThread() function, this line of code is running Toast.makeText(getApplicationContext(), "Listening" it is shown that my server is listening to incoming connection
but when I'm using other client to connect to this server, then client are showing "paired" but on the server there is nothing shown, but the connection was actually successfull.
from the line
//This will block while listening until a BluetoothSocket is returned//or an exception occurs and //If a connection is acceptedis not running, because the toast did not coming out.
this function is called from MainActivity Threads and was putted on a button. I don't think pasting all the code here will be good, but here is the button codes. if there is anything you need to see, simply ask me.
serverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListeningThread t = new ListeningThread();
t.start();
}
});
I am currently trying to receive data on my android smartphone (version 4.4.4) send from my RFduino (some kind of arduino) via Bluetooth. Therefore i made a small android application.
Now everything works fine, until i try to connect my BluetoothSocket. First i got the an IOException: read failed -1 which i tried to solve like this:
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Which worked. But now my application just freezes after i call connect(). I know that this is because the method blocks until it has found a connection, but why does this not connect?
My RFduino uses BluetoothBLE (low energy): Do i have to use the BluetoothGatt classes as counter-part?
Here is my code:
public BluetoothConnection(Activity parentActivity) {
this.mActivity = parentActivity;
findBluetooth();
openBluetooth();
}
private void findBluetooth() {
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
}
if (!this.mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
this.mActivity.startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("RFduino")) {
this.mBluetoothDevice = device;
break;
}
}
}
}
private void openBluetooth() {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
BluetoothSocket tmp = this.mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
this.mBluetoothSocket = new NativeBluetoothSocket(tmp);
this.mBluetoothSocket.connect();
} catch (IOException e) {
// try the fallback
Log.w("BT", "Had to use fallback method!");
try {
this.mBluetoothSocket = new FallbackBluetoothSocket(this.mBluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
this.mBluetoothSocket.connect();
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
try {
this.mInputStream = this.mBluetoothSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
While NativeBluetoothAdapter and FallbackBluetoothAdapter are depicted in the thread i posted above.
Thanks for any suggestions.