Greetings Stack Overflow community,
I am writing an android app that reads some data off of an HC05 bluetooth module.
I am just trying to read one byte but it just hangs there for a few minutes before it crashes. Maybe its a hardware problem, but perhaps there is some error in my code I do not see. If anybody has a clue as to why I would not be able to read from this module I would greatly appreciate the input.
Thanks!
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getName().equals("HC-05")) {
BluetoothDevice device = iterator;
try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);} catch (IOException ex) {}
try {btSocket.connect();} catch (IOException ex) {}
if (btSocket.isConnected()) {
Toast.makeText(getApplicationContext(), "Connected to HC05", Toast.LENGTH_SHORT).show();
//Write 'r' to arduino to tell it to send data.
try {
outStream = btSocket.getOutputStream();
outStream.write('r');
} catch (IOException ex) {}
int byteCount = 1;
byte[] rawBytes = new byte[byteCount];
try {
inputStream= btSocket.getInputStream();
int a = inputStream.read(rawBytes, 0, 1);
}
Did you try using a Bluetooth terminal app for android? This way you can find out if it's a hardware or software issue.
You could try this app:
https://play.google.com/store/apps/details?id=Qwerty.BluetoothTerminal
Related
So I have one question, I have to do a chat application in school, with a feature which allows me to see my old conversations offline like in WhatsApp.
It kind of works after I turn immediately internet off and when I start then my app I can see my conversations, but after some time the chats are not loading anymore. I searched a bit on the internet and have read I have to save the chat as a file to the internal storage, but how do I do it I couldn't find anything about that.
This is my code for loading my messages online and offline
public void loadConversations() {
boolean result;
try {
FileInputStream fileInputStream = getApplicationContext().openFileInput("CONVERSATIONS");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
this.conversations = (HashMap<String, ArrayList<Message>>) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
result = true;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
result = false;
}
if (this.conversations == null) {
this.conversations = new HashMap<>();
}
Log.d(TAG, "loadConversations result: " + result + " size: " + this.conversations.size());
}
public void persistConversations() {
boolean result;
try {
FileOutputStream fileOutputStream = getApplicationContext().openFileOutput("CONVERSATIONS",getApplicationContext().MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this.conversations);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
}
Log.d(TAG, "persistConversations result: " + result);
}
maybe someone can give me an pointer.
There is the best way to make a chat app with firebase real-time database and when a user is offline (No internet connection). Firebase created a local database and store all the details in local and show your user-details and your messages. You don't need to create a separate database. Follow this link to know about firebase realtime database :- https://firebase.google.com/docs/database/android/start/?gclid=EAIaIQobChMInMag3qiV4wIVAh4rCh2fJQWAEAAYASABEgIfFPD_BwE
I have been working on trying to get a Bluetooth device like a keyboard or a remote to connect to an android device. More specifically when this program runs for the first time it would scan for Bluetooth devices and attempt to pair and connect with one that it finds. I have tried seemingly every possible way to accomplish this but I am only able to pair the device, not connect it completely.
I have tried the examples in the Android Bluetooth guide and many others. One consistency is the javi.io error I get when the BluetoothSocket is calling connect.
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:505)
at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:482)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:324)
at BTConnectThread.run(BTConnectThread.java:61)
I have tried different UUIDs. Some I generated myself others I pulled from the devices. I also tried writing code assuming both are acting as servers that mirrors mostly what I am doing here and what is in the Android Bluetooth guide. have tried all variations of calling createBond() on the device. All attempts leave the device paired/bonded but not connected. Any help is greatly appreciated.
` public BTConnectThread(BluetoothDevice bluetoothDevice) {
BluetoothSocket tempSocket = null;
try {
// tempSocket = bluetoothDevice.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
// tempSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
//Magic?
Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket",
new Class[]{int.class});
tempSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);
} catch (Exception e) {
e.printStackTrace();
}
m_bluetoothSocket = tempSocket;
}
public void run() {
//cancel discovery
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null)
bluetoothAdapter.cancelDiscovery();
//TODO: Try brute force approach. Loop until it connects.
//TODO: Try a fallback socket.
try {
m_bluetoothSocket.connect();
Log.d(TAG, "Connection Established");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
Log.d(TAG, "Fail to connect!", connectException);
try {
m_bluetoothSocket.close();
} catch (IOException closeException) {
Log.d(TAG, "Fail to close connection", closeException);
}
return;
}
}
public void cancel() {
try {
m_bluetoothSocket.close();
} catch (IOException e) {
}
}`
Bluetooth connection require to create more than 3 threads, so you can try to use https://android-arsenal.com/details/1/1859.
Kotlin
Connect Function
fun connect(btDevice: BluetoothDevice?){
val id: UUID = btDevice?.uuids?.get(0)!!.uuid
val bts = btDevice.createRfcommSocketToServiceRecord(id)
bts?.connect()
}
Call this in main thread
val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device = bluetoothAdapter.getRemoteDevice("your mac address")
connect(device)
I'm developing an Android app than can transmit data to a 4.0 Bluetooth serial device. I'm guiding by LeGatt android sample project (http://developer.android.com/samples/BluetoothLeGatt/index.html). In this project, they connect to the device, but nothing about transmission data.
For 2.0 bluetooth I can create a Socket, InputStream and OutputStream to transmit the data, something like this:
protected BluetoothSocket mySocket = null;
private InputStream MyInStream;
private OutputStream MyOutStream;
try {
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mBluetoothDevice, Integer.valueOf(1));
} catch (Exception e) {
textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK");
}
mySocket = tmp;
try {
mySocket.connect();
} catch (IOException e) {
textViewLog.append("\n"+e.getMessage());
textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK 2");
}
try {
MyInStream = mySocket.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
try {
MyOutStream = mySocket.getOutputStream();
} catch (IOException e) {
textViewLog.append("\nERROR: "+e.getMessage());
}
try {
MyOutStream.write((letra+"\r").getBytes());
} catch (IOException e) {
textViewLog.append("\nERROR: "+e.getMessage());
}
But in 4.0 Bluetooth I can't create the Socket, because this method doesn't works
try {
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mBluetoothDevice, Integer.valueOf(1));
} catch (Exception e) {
textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK");
}
Can someone help me to reach the data transmission using my 4.0 bluetooth device.
Android BLE works entirely different from the Bluetooth stack, read about BLE in Wikipedia.
To send a data using BLE, you need to place your data in characteristics and send it using the gatt!
1st, you need to check your BLE device, which characteristic is used for sending data and used that characteristics for sending data!
byte[] data; //Place your data into this array of byte
characteristic.setValue(data);
gatt.writeCharacteristic(characteristic);
Please take note that Android BLE stack is buggy, you can only writeCharacteristics once at a time, as mention in the link below!!
You can check this post about Android BLE, it will give you a clear understanding of the how the Android BLE callbacks work!
Android BLE, read and write characteristics
What I DO :
Write an upload program using java.net.Socket at Android Mobile
What I WANT:
Connect the Server, When IOException happens(such as the bad network state,no network etc.),try to connect the server three times
What The Question:
Close the WIFI or Mobile GPRS and just run it, No IOexception happened and APP just stop at this point long long time.
Just See My Code:
try {
do {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(API.UPLOAD_SERVER, API.UPLOAD_PORT);
socket.setPerformancePreferences(1, 0,0);
socket.setSoTimeout(1000);
socket.connect(socketAddress, 2000);
attempt = 3;
} while (attempt < 3);
mListener.onStart();
} catch (SocketException e) {
Log.e("UploadTask","exception");
return;
} catch (UnknownHostException e) {
return;
} catch (IOException ioe) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return ;
}
attempt++;
if (attempt == 3) {
return;
}
}
Help Me or ...:
I hope someone can help me,I will wait your answer online, Thanks.
you have nothing output or exception if you close WIFI or GPRS. Does this mean you app will run over or you code will stay in one sentence,for example, the "connect" method?
I have a suggestion. If you want to explore the API of android, that's OK. OR
Maybe you can test Connectivity before your socket connect.
private boolean isOpenNetwork() {
ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
hope this can help..
PS: I have no idea about the direct solution to your question, for I have no idea about the socket realize detail. Maybe someone else can explain it.
Assuming that the "connect" method succeeds (which can happen), the API is build in a way that you get IOException(s) when actually reading/writing to the streams of the socket.
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(API.UPLOAD_SERVER, API.UPLOAD_PORT);
socket.setPerformancePreferences(1, 0,0);
socket.setSoTimeout(1000);
socket.connect(socketAddress, 2000);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Now for example, if you want to read some data
int data;
try( data = is.read() ){
// Usual processing
} catch( IOException ){
// Disconnected... try reconnecting etc.
}
EDITED:
Im developing SMS application in java for reading SMS.Im sending AT commands to GSM mode for sending an SMS,messages is sending successfully ,but im not getting any response from the modem.If i send the AT commands through Hyperterminal im getting the response.Whats the exact problem?
InputStream inputStream;
OutputStream out;
this.inputStream = serialPort.getInputStream();
this.out = serialPort.getOutputStream();
out.write(("AT"+"\r").getBytes());
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
out.write(("AT+CMGF=1"+"\r").getBytes());
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
out.write(("AT+CMGS=\""+"+91xxxxxxxxxx"+"\""+"\r").getBytes());
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
out.write(("TEST "+cntrlZ).getBytes());
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
//Im using SerialPortEventListener to read the input from modem
int a = inputStream.available();
System.out.println(inputStream.available() + " BYTES AVAILABLE ");
inputStream.read(readBuffer, 0, a);
I also tried to read after sending each AT commands,but im not getting anything as a response from the modem.
Issues receving in RXTX
After setting the flow control for the serial port its working fine.
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
Please make sure that you have installed all libraries required by SMSlib and your modem is on supported modems list. Having supported modem is not required, but can eliminate compatibility problem right off the bat.
Also you should verify if your modem is connected properly. You could perform some operations on it directly, via AT commands.