altosdroid: fix a connection retry having a null pointer
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / TelemetryService.java
index ccb04de03860e8905adace8fa6ee7b587d6bc3a3..1fa62d870f7944395c2d3ef4847869222b08cb4a 100644 (file)
@@ -110,8 +110,11 @@ public class TelemetryService extends Service {
                                s.startAltosBluetooth();
                                break;
                        case MSG_DISCONNECTED:
-                               if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
-                               s.stopAltosBluetooth();
+                               // Only do the following if we haven't been shutdown elsewhere..
+                               if (s.device != null) {
+                                       if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
+                                       s.stopAltosBluetooth();
+                               }
                                break;
                        case MSG_TELEMETRY:
                                s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
@@ -158,8 +161,14 @@ public class TelemetryService extends Service {
                        mAltosBluetooth = new AltosBluetooth(device, mHandler);
                        setState(STATE_CONNECTING);
                } else {
+                       // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
+                       // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
+                       // to ourselves in a few seconds time that will ultimately call this method again.
+                       // ... then we tear down the existing connection.
+                       // We do it this way around so that we don't lose a reference to the device when this method
+                       // is called on reception of MSG_CONNECT_FAILED in the handler above.
+                       mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
                        stopAltosBluetooth();
-                       mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 1000);
                }
        }