Android bluetooth send message working first time only

2024/10/10 18:24:00

I need to send string message from Raspberry PI to Android device. I am getting message first time only. After that it does not work at all. I am using PYTHON code in Raspberry PI. After first time, it is unable to search for a bluetooth device, which is running that UUID. However, if I restart Android application - again it works fine for first time. I am using AcceptThread as suggested here. I have not used ConnectThread or ConnectedThread in my application, as I need only incoming messages. Do I need to close something on Pause or Destroy. Or, do I need to do something which is not mentioned in that page?

Here is that code:

private UUID MY_UUID = UUID.fromString("1e0ca4ea-299d-4335-93eb-27fcfe7fa848");
private AcceptThread acceptThread;private class AcceptThread extends Thread {private final BluetoothServerSocket mmServerSocket;public AcceptThread() {// Use a temporary object that is later assigned to mmServerSocket,// because mmServerSocket is finalBluetoothServerSocket tmp = null;try {// MY_UUID is the app's UUID string, also used by the client codetmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(TAG, MY_UUID);} catch (IOException e) { }mmServerSocket = tmp;}public void run() {BluetoothSocket socket = null;// Keep listening until exception occurs or a socket is returnedwhile (true) {try {socket = mmServerSocket.accept();} catch (IOException e) {break;}// If a connection was acceptedif (socket != null) {// Do work to manage the connection (in a separate thread)manageConnectedSocket(socket);try {mmServerSocket.close();}catch(IOException e){}break;}}}/** Will cancel the listening socket, and cause the thread to finish */public void cancel() {try {mmServerSocket.close();} catch (IOException e) { }}
}

I am not using PI message, just logging a string. As mentioned above, it works first time:

private void manageConnectedSocket(BluetoothSocket socket) {Log.i(TAG, "Hurray!! I am here");//acceptThread.cancel();
}

Here is the PYTHON code in Raspberry PI:

import sys
import bluetoothuuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"service_matches = bluetooth.find_service( uuid = uuid )if len(service_matches) == 0:print "couldn't find the BluetoothWithPi service"sys.exit(0)first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]print "connected to \"%s\" on %s" % (name, host)sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((host, port))
sock.send("Hello from Raspberry PI!!")
sock.close()

First time it displays 'Connected to ...' message. Second time it displays 'Couldn't find...' message.

Answer

We just need to add some code into manageConnectedSocket block. Basically we need to cancel the acceptThread if not null and restart the service:

private void manageConnectedSocket(BluetoothSocket socket) {Log.i(TAG, "Hurray!! I am here");//if (acceptThread != null) {acceptThread.cancel();acceptThread = null;}//if (acceptThread == null) {acceptThread = new AcceptThread();acceptThread.start();}
}
https://en.xdnf.cn/q/118422.html

Related Q&A

Scraping data from href

I was trying to get the postcodes for DFS, for that i tried getting the href for each shop and then click on it, the next page has shop location from which i can get the postal code, but i am able to g…

Numpy - how to sort an array of value/key pairs in descending order

I was looking at the problem Fastest way to rank items with multiple values and weightings and came up with the following solution, but with two remaining issues:import numpy as np# set up values keys …

How to extract certain under specific condition in pandas? (Sentimental analysis)

The picture is what my dataframe looks like. I have user_name, movie_name and time column. I want to extract only rows that are first day of certain movie. For example, if movie as first date in the ti…

Flask app.run method does not work with WinPython 3.11.1 and next.js application: fetch failed

When using WinPython 3.10.5 I am able to debug my flask & next.js application using the flask debug mode (to enable hot reloads): app.run(debug=True, host=host, port=port)However, when using WinPyt…

Pythonic way to assign global administrator roles for Azure Active Directory

What specifically needs to be changed in the Python 3 code below in order to successfully assign the Global Administrator role for an Azure Active Directory Tenant to a given service principal? We tri…

Pandas calculating age from a date

I really need help with this one. My previous post was very bad and unclear - Im sorry - I wish I could delete but hopefully this one will be better.I need to calculate the age based off of a date (se…

Create new folders within multiple existing folders with python

I am looking for a way to create new folders within multiple existing folders. For example I have folders a,b,c.. etc and I want to create a new folder inside each of these existing folders and name th…

extract a column from text file

I have a a text file (huge amount of float numbers) with 25 columns. I want to extract column 14 and divide it by column 15. I could not extract this two columns. Codes:with open(sample for north.txt) …

kivy buildozer Compile Error pythonforandroid.toolchain

Compile platformCommand failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=main -- bootstrap=sdl2 --requirements=kivy,python3 --arch armeabi- v7a --copy-libs --color=always --…

Django Error: No FlatPage matches the given query

SITE_ID = 1and (r, include(django.contrib.flatpages.urls)), is in urls.py.What can I do to fix this error? Django is still displaying this error - I have googled and I cant find anything.File urls.pyf…