Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not trying to connect when Bluetooth is disabled. #363

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
*.DS_Store
.idea/
15 changes: 15 additions & 0 deletions build-extras.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
ext.postBuildExtras = {
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
allprojects {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
}
}
}

3 changes: 3 additions & 0 deletions plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</config-file>

<!-- Enforces java 7 or higher: https://github.com/cvuser0/cordova-plugin-java7-->
<source-file src="build-extras.gradle" target-dir="../android" />

</platform>

<platform name="ios">
Expand Down
12 changes: 5 additions & 7 deletions src/android/com/megster/cordova/BluetoothSerial.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public class BluetoothSerial extends CordovaPlugin {
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

LOG.d(TAG, "action = " + action);
//LOG.d(TAG, "action = " + action);

if (bluetoothAdapter == null) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Expand All @@ -110,14 +110,12 @@ public boolean execute(String action, CordovaArgs args, CallbackContext callback

} else if (action.equals(CONNECT)) {

boolean secure = true;
connect(args, secure, callbackContext);
connect(args, true, callbackContext);

} else if (action.equals(CONNECT_INSECURE)) {

// see Android docs about Insecure RFCOMM http://goo.gl/1mFjZY
boolean secure = false;
connect(args, secure, callbackContext);
connect(args, false, callbackContext);

} else if (action.equals(DISCONNECT)) {

Expand Down Expand Up @@ -350,7 +348,7 @@ private void connect(CordovaArgs args, boolean secure, CallbackContext callbackC
callbackContext.sendPluginResult(result);

} else {
callbackContext.error("Could not connect to " + macAddress);
callbackContext.error("Could not connect to " + macAddress + "(device not found/unreachable)");
}
}

Expand Down Expand Up @@ -400,7 +398,7 @@ public void handleMessage(Message msg) {
// Log.i(TAG, "Wrote: " + writeMessage);
break;
case MESSAGE_DEVICE_NAME:
Log.i(TAG, msg.getData().getString(DEVICE_NAME));
Log.i(TAG, "device name: " + msg.getData().getString(DEVICE_NAME));
break;
case MESSAGE_TOAST:
String message = msg.getData().getString(TOAST);
Expand Down
84 changes: 58 additions & 26 deletions src/android/com/megster/cordova/BluetoothSerialService.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
*
* <p>
* This code was based on the Android SDK BluetoothChat Sample
* $ANDROID_SDK/samples/android-17/BluetoothChat
*/
Expand Down Expand Up @@ -58,7 +58,8 @@ public class BluetoothSerialService {

/**
* Constructor. Prepares a new BluetoothSerial session.
* @param handler A Handler to send messages back to the UI Activity
*
* @param handler A Handler to send messages back to the UI Activity
*/
public BluetoothSerialService(Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
Expand All @@ -68,7 +69,8 @@ public BluetoothSerialService(Handler handler) {

/**
* Set the current state of the chat connection
* @param state An integer defining the current connection state
*
* @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
Expand All @@ -79,22 +81,30 @@ private synchronized void setState(int state) {
}

/**
* Return the current connection state. */
* Return the current connection state.
*/
public synchronized int getState() {
return mState;
}

/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
if (D) Log.d(TAG, "start");

// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}

setState(STATE_NONE);

Expand All @@ -114,19 +124,30 @@ public synchronized void start() {

/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*
* @param device The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, "connect to: " + device);
if (D) Log.d(TAG, "Connecting to: " + device);


if (mAdapter == null || !mAdapter.isEnabled()) {
Log.e(TAG, "Bluetooth is disabled! Not connecting");
return;
}

// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mState == STATE_CONNECTING && mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}

// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
Expand All @@ -136,17 +157,24 @@ public synchronized void connect(BluetoothDevice device, boolean secure) {

/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) {
if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}

// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
Expand Down Expand Up @@ -202,6 +230,7 @@ public synchronized void stop() {

/**
* Write to the ConnectedThread in an unsynchronized manner
*
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
Expand All @@ -221,6 +250,7 @@ public void write(byte[] out) {
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
Log.e(TAG, "Connection failed!");
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothSerial.MESSAGE_TOAST);
Bundle bundle = new Bundle();
Expand Down Expand Up @@ -259,7 +289,7 @@ private class AcceptThread extends Thread {

public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure":"Insecure";
mSocketType = secure ? "Secure" : "Insecure";

// Create a new listening server socket
try {
Expand Down Expand Up @@ -369,31 +399,31 @@ public void run() {
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a successful connection or an exception
Log.i(TAG,"Connecting to socket...");
Log.i(TAG, "Connecting to socket...");
mmSocket.connect();
Log.i(TAG,"Connected");
} catch (IOException e) {
} catch (IOException | NullPointerException e) {
Log.e(TAG, e.toString());

// Some 4.1 devices have problems, try an alternative way to connect
// See https://github.com/don/BluetoothSerial/issues/89
try {
Log.i(TAG,"Trying fallback...");
mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice,1);
Log.i(TAG, "Trying fallback...");
mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1);
mmSocket.connect();
Log.i(TAG,"Connected");
} catch (Exception e2) {
Log.e(TAG, "Couldn't establish a Bluetooth connection.");
try {
mmSocket.close();
} catch (IOException e3) {
} catch (IOException | NullPointerException e3) {
Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e3);
}
connectionFailed();
return;
}
}

Log.i(TAG, "Successfully connected!");

// Reset the ConnectThread because we're done
synchronized (BluetoothSerialService.this) {
mConnectThread = null;
Expand All @@ -406,7 +436,7 @@ public void run() {
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
} catch (IOException | NullPointerException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
Expand Down Expand Up @@ -474,7 +504,8 @@ public void run() {

/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
Expand All @@ -497,3 +528,4 @@ public void cancel() {
}
}
}