diff --git a/app/src/main/java/com/codigoparallevar/minicards/bridge/ProgramakerBridgeService.java b/app/src/main/java/com/codigoparallevar/minicards/bridge/ProgramakerBridgeService.java index dfd70c4..151aa8f 100644 --- a/app/src/main/java/com/codigoparallevar/minicards/bridge/ProgramakerBridgeService.java +++ b/app/src/main/java/com/codigoparallevar/minicards/bridge/ProgramakerBridgeService.java @@ -16,6 +16,7 @@ import com.programaker.api.ProgramakerApi; public class ProgramakerBridgeService extends Service { public static final String BridgeUserNotificationChannel = "PROGRAMAKER_BRIDGE_USER_NOTIFICATION"; public static final CharSequence BridgeUserNotificationChannelName = "User notifications"; + private static final long WAIT_TIME_BEFORE_RESTART_MILLIS = 10000; // 10s private ProgramakerAndroidBridge bridge = null; private static final String LogTag = "PM BridgeService"; @@ -25,7 +26,14 @@ public class ProgramakerBridgeService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { + Toast.makeText(this, "Starting bridge", Toast.LENGTH_SHORT).show(); + connectBridge(); + // If we get killed, after returning from here, restart + return START_STICKY; + } + + private void connectBridge() { ConfigManager config = new ConfigManager(this); String token = config.getToken(); @@ -75,6 +83,7 @@ public class ProgramakerBridgeService extends Service { }, ex -> { Log.e(LogTag, "Error establishing bridge connection: " + ex, ex); + ProgramakerBridgeService.this.stopSelf(); } ) ); @@ -82,8 +91,7 @@ public class ProgramakerBridgeService extends Service { }, () -> { // On completed ProgramakerBridgeService.this.bridge = null; - Log.e(LogTag, "Bridge stopped, stopping service"); - ProgramakerBridgeService.this.stopSelf(); + onBridgeFailedAfterConnected(); }); } catch (Throwable ex) { @@ -93,10 +101,16 @@ public class ProgramakerBridgeService extends Service { }, "ServiceStartArguments"); thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND); thread.start(); - Toast.makeText(this, "Starting bridge", Toast.LENGTH_SHORT).show(); + } - // If we get killed, after returning from here, restart - return START_STICKY; + private void onBridgeFailedAfterConnected() { + Log.e(LogTag, "Bridge stopped after connected. Waiting 10s then restarting"); + try { + Thread.sleep(WAIT_TIME_BEFORE_RESTART_MILLIS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + connectBridge(); } @Override