I would like to implement an application to receive a file from a Bluetooth device.
Before receiving, a notification will be raised to accept an incoming file request.
From there, i would like to activate "accept" and download the file automatically without raising an accept dialog when the user receive a second file from another Bluetooth paired device, without notification disturbance when the user launchs an application.
I developed an app that include this kind of task, and you can use BluetoothChat example.
You must set the secure flag to false:
`
boolean secure = false;
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
mmServerSocket = tmp;
}`
And then read the buffer from the InputStream that you can find in ConnectedThread:
while (true) {
try {
bytes = mmInStream.read(buffer);
/*write bytes in a file*/
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
BluetoothChatService.this.start();
break;
}
}
You can try using the Bluetooth socket connection to set a client server TCP like connection.
ON ROOTED DEVICES, You can just install only two apps on your phone to achieve your goal.
XPosed Installer
Auto-Accept
This way you hook System service.
import android.util.*;
import de.robv.android.xposed.*;
import de.robv.android.xposed.callbacks.XC_LoadPackage.*;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
public class Tutorial implements IXposedHookLoadPackage
{
private String TAG="TUTORIAL";
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.bluetooth"))
{
Log.i(TAG,"Not: "+lpparam.packageName);
return;
}
Log.i(TAG,"Yes "+lpparam.packageName);
findAndHookMethod("com.android.bluetooth.opp.BluetoothOppManager", lpparam.classLoader, "isWhitelisted", String.class,new XC_MethodHook() {
#Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Log.v(TAG,"HOOK DONE");
param.setResult(true); /* you can compare the sender address(String) with your computer and determine if you return true or just allow the original method to be called after this returns.*/
}
});
}
}
For more information, please visit my answer in SO.
I'll post some direct links here.
Links
Dropbox link of the auto accepting app
Dropbox link of the project files (zip)
Xposed apk site
Towelroot site to root your phone
Auto-Accept github repository
Related
I would like to create an application which can connect to a Bluetooth Headset via the Hands Free Protocol (HFP). I followed the Android example and have now a BluetoothSocket with its Input and OutputStream. Below you see my read and write methods (read method is executed by another Thread)
public void read() {
while (true) {
Log.d("ME", "Waiting for data");
try { // read until Exception is thrown
numBytes = inStream.read(dataBuffer);
String str = new String(dataBuffer,0,numBytes);
msgHandler.obtainMessage(numBytes, str).sendToTarget();
} catch (Exception e) {
Log.d("ME", "Input stream was disconnected", e);
break; // BluetoothDevice was disconnected => Exit
}
}
}
public void write(byte[] bytes) {
try {
outStream.write(bytes);
outStream.flush();
Log.e("ME", "Wrote: " + new String(bytes));
} catch (IOException e) {
Log.e("ME", "Error occurred when sending data", e);
}
}
When the connection is opened the Bluetooth headset sends AT+BRSF=191 over the InputStream. I tried to response with +BRSF:20\r but here is my problem. After that the device does not send any other data over the InputStream. It does not come to an Exception - it's more like the device does not know how to responde to my message. Do I send the wrong data? I have all the information from here: (HF = Hands-Free Unit AG = Audio Gateway)
Do you have any ideas what I did wrong? Have I missed something?
EDIT: These are my write calls:
write("+BRSF: 191\r");
write("OK\r");
You were missing the OK response. According to this document, the OK-code consists of a windows-style newline (CR LF), the literal OK and then another newline.
Do note that other commands are terminated by a carriage return only. For more information on the hands-free protocol, you can refer to that very document you linked in your post.
Example code:
public static final String OK = statusCode("OK")
public static final String ERROR = statusCode("ERROR")
public static String statusCode(String code) {
return "\r\n" + code + "\r\n";
}
public static String command(String cmd) {
return cmd + "\r";
}
Now you can use OK and ERROR in your code as constants, and you can use the statusCode method for other status codes.
I am writing a program for a new vehicle security app. the app allows the user to control lock/unlock operations via his phone app. Lets say the user's phone Bluetooth is switched off at first. If that's the case, when he opens the app, the phone bluetooth adapter should be automatically switched on and should connect with the bluetooth module fixed in to the vehicle.
according to the code I have done, the programatic enabling of the BT adapter of phone works fine. But the connection to the vehicle BT module does NOT happen.
But if the user opens the app while the phone BT adapter is already switched on, then the connection establishing between the vehicle and phone happens automatically.
I need to know why the connection does NOT happen when the BT adapter is turned on programmatically.
Note - the phone and the vehicle BT module is paired. The bluetooth modules mac address is hard coded in the coding.
The coding is as follows. I only pasted the necessary parts. I hope every needed to understand and solve my problem is here. The way I posted the code is pretty messed up. Sorry about that. Hope it's clear. I'm new to this.
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert bluetooth devices MAC address
private static String address = "00:19:5D:EF:03:79";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
btAdapter.enable();
#Override
public void onResume() {
super.onResume();
btAdapter.enable();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Make sure Discovery isn't going on when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
There might be a timing problem, onCreate and onResume are called in very short order. In the case that the BT is not enabled the code in onResume might be called before the BT service is online.
My advice: Try to delay the initiation a few seconds by putting the code in a Runnable.
private Handler mHandler = new Handler();
public void onCreate() {
[...]
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
btAdapter.enable();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Make sure Discovery isn't going on when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}, 5000); // 5 second delay
[...]
Caveats: This works really bad if you exit the app promptly after startup. Put the runnable in a member variable and call mHandler.removeCallback(Runnable) in onDestroy().
I'm trying to establish a bluetooth communication between an android phone/tablet (4.0.3), and a bluetooth device, which is an earring reader (Destron Fearring DTR3E, in case you want to know, which I don't suppose you do).
I paired the phone with the reader (the reader has the pairing passcode on a tag) from the bluetooth settings, bluetooth is on of course, and now I'm trying to listen to reads from the device, by means of BluetoothServerSocket. The problem is that the accept call never returns, so obviously I am doing something wrong. The communication is done using RFCOMM.
Code:
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
String uuid = "00001101-0000-1000-8000-00805F9B34FB";
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("pdfParserServer", UUID.fromString(uuid));
} catch (Exception e) {
e.printStackTrace();
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
Is there something I am missing?
Thank you!
The only reason that could cause the code never to come back from accept is that, the device "Destron Fearring DTR3E" you are trying to connect to, has actually a bluetoothserver socket and not a bluetooth client, hence, the device might be waiting for you to actually connect to it, in stead of you creating a bluetoothserver socket and waiting for it to connect to your android device, you should read the specs on the device and make sure that actually is you the one that has to open a connection on "Destron Fearring DTR3E" socket...
Hope this helps...
Regards!
I have the following setup:
An Android device uses a 'Client' socket to connect to a remote embedded device, The Android application uses the following code snippet to connect to the embedded device.
On the embedded device uses MindTree BT stack, where server serial socket is prepared according to some properties in the device, which the Android application is familiar with, the connection defined on the embedded device, is not secured!!
The combination of both applications works on:
2 LG phones different models (version code < 10 uses the "Normal method")
2 HTC's different models (version code < 10 uses the "Workaround method")
Pantech Tablet (version code < 13 uses the "Workaround method")
Today, I've tried the application on Samsung S3, Motorola MB886, and a Nexus 7...
All resulted in a "Permission Denied" when calling to socket.connect()... (I have the proper permissions in the manifest, otherwise it would not work on the other devices.)
All the new devices I've tested on are version code > 4.0, so I'm wondering:
Does anyone know about any changes in the API?
Perhaps Android 4.0+ forces security?
It seem that the error occur in the Bonding state, since I can see on the embedded program logs...
Any insights?
The code:
public final synchronized int connectToDevice(int connectingMethod)
throws BluetoohConnectionException {
if (socket != null)
throw new BadImplementationException("Error socket is not null!!");
connecting = true;
logInfo("+---+ Connecting to device...");
try {
lastException = null;
lastPacket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Normal();
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_StandardConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Reflection(1);
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_ReflectiveConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
throw new BluetoohConnectionException("Error creating RFcomm socket for BT Device:" + this
+ "\n BAD connectingMethod==" + connectingMethod);
} finally {
connecting = false;
}
}
protected void onConnetionEstablished() {
logInfo("+---+ Connection established");
}
private synchronized void listenForIncomingSPP_Packets() {
if (socketListeningThread != null)
throw new BadImplementationException("Already lisening on Socket for BT Device" + this);
logInfo("+---+ Listening for incoming packets");
socketListeningThread = new Thread(socketListener, "Packet Listener - " + bluetoothDevice.getName());
socketListeningThread.start();
}
private BluetoothSocket fetchBT_Socket_Normal()
throws BluetoohConnectionException {
try {
logInfo("+---+ Fetching BT RFcomm Socket standard for UUID: " + uuid + "...");
return bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private BluetoothSocket fetchBT_Socket_Reflection(int connectionIndex)
throws BluetoohConnectionException {
Method m;
try {
logInfo("+---+ Fetching BT RFcomm Socket workaround index " + connectionIndex + "...");
m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
return (BluetoothSocket) m.invoke(bluetoothDevice, connectionIndex);
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private void connectToSocket(BluetoothSocket socket)
throws BluetoohConnectionException {
try {
logInfo("+---+ Connecting to socket...");
socket.connect();
logInfo("+---+ Connected to socket");
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
logError("Error while closing socket", e1);
} finally {
socket = null;
}
throw new BluetoohConnectionException("Error connecting to socket with Device" + this, e);
}
}
After very long long time of investigating the matter I've found one reason for the error... on some Android devices the auto Bluetooth peering is not enabled/allowed.
So, apparently except for two connection method, there are also two Bluetooth adapter enabling method, one would be to throw an intent to ask the system to turn the adapter on, and the other is to call onto the BluetoothAdapter.enable() method, which enables the Bluetooth silently.
The first method, pops a confirmation dialog, and require user interaction while the other does not, and while not showing the Bluetooth enabling confirmation dialog, also the peering confirmation is not shown, which causes the connection error.
Using the first adapter enabling method solves the problem on most of the devices, like the Nexus 7, Samsung S3, and a few others, but on some devices there is still an issue, and I'm not really sure why, but this is much better since many devices are now working with the new implementation.
I have an Android Bluetooth application which manages a couple of remote devices(Capsules).
Writing data to the socket output stream of a Capsule worked yesterday, and after medium scale refactoring to the Android application only, I get the following error:
java.lang.IllegalMonitorStateException: attempt to unlock read lock, not locked by current thread.
Here is the socket creation code:
public final void connectWithCapsule(Capsule capsule)
throws Exception {
BluetoothSocket socket = capsulesSockets.get(capsule);
if (socket == null) {
try {
// Method m = capsule.getBT_Device().getClass().getMethod("createRfcommSocket", new Class[]{int.class});
// socket = (BluetoothSocket) m.invoke(capsule.getBT_Device(), Integer.valueOf(17));
socket = capsule.getBT_Device().createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch (Exception e) {
logError("Error creating RFcomm socket", e);
throw e;
}
capsulesSockets.put(capsule, socket);
}
try {
socket.connect();
} catch (IOException e) {
logError("Error connecting socket", e);
try {
socket.close();
} catch (IOException e1) {
logError("Error closing socket", e1);
}
capsulesSockets.remove(capsule);
throw e;
}
}
and the model which manages the in/out streams:
public final class KitBT_ConnectionModel {
private final OutputStream[] outputStreams;
private final InputStream[] inputStreams;
public KitBT_ConnectionModel(OutputStream[] outputStreams, InputStream[] inputStreams) {
super();
this.outputStreams = outputStreams;
this.inputStreams = inputStreams;
}
public void transmitData(byte[] bs)
throws IOException {
for (OutputStream outputStream : outputStreams) {
outputStream.write(bs); // THIS LINE THROWS THE EXCEPTION
outputStream.flush();
}
}
public InputStream[] getInputStreams() {
return inputStreams;
}
}
Note: I do not perform any action with both of the streams, and the first write causes the exception.
First thing that pops to mind is which thread puts the read lock and when?
I've tried to play around with the threads which call the socket creation, and the streams transactions, I've made sure, 100% sure they have both been accessed by the same thread (and also tried accessing with different threads), but this exception persists.
Please enlighten me...
HAAAAAAAAAAAAAAAAAAa.........
Darn this LG phones!!!!
I gave the phone a hard reboot, removed the battery and started it over, and it works again...
turning the Bluetooth off and on didn't do the trick! I've been doing it for the past day or so.
God damn it nearly 24 hours of waste for nothing....
How messed up can these products be!
at least it works now!