0

I'm running into tons of problems using RxAndroidBle when events like back button press happen and I was wondering what the best way to pause execution of the back button is. I basically want to create a lock until a particular bluetooth operation completes. Once the operation completes I want to finish the execution of the back button. Anyone have any ideas?

David Carek
  • 1,103
  • 1
  • 12
  • 26

1 Answers1

3

Just override the back button and use some flag? E.g.

private boolean delayedBack = false; // as member field

...other Activity code

@Override
public void onBackPressed(){
   if(someCondition)
      super.onBackPressed();
    else
      delayedBack = true;  
}

Then when some asynchronous operation finishes just check that flag:

 if(delayedBack){
   super.onBackPressed();
   delayedBack = false; // in case you don't want to finish the Activity
  }

Of course instead of using super.onBackPressed(); which in most cases will finish the Activity you can perform any other action you'd perform when the user hits the back button.

Droidman
  • 11,485
  • 17
  • 93
  • 141
  • overriding `onBackPressed` is really dangerous, you could block the navigation of your app indefinetely if the flag won't be resetted after some point for any reason. This is a viable solution but requires a lot of effort to make it "bug" free – MatPag Sep 20 '17 at 15:02
  • @MatPag that's why it is the responsibility of the developer to test all the use-cases thoroughly – Droidman Sep 20 '17 at 15:04
  • I have been somewhat cornered into this approach because of errors from the RxAndroidBle library. – David Carek Sep 20 '17 at 15:06
  • I agree with this answer. I would like to add though: overriding in this manner is not blocking the UI thread per say, but it is blocking the user experience (as it will seem like the app is making the device unresponsive). Also, iirc Android 6.0+ has an additional back button feature that can force close apps. – Jon Sep 20 '17 at 15:07
  • and the OP states `I basically want to create a lock until a particular bluetooth operation completes` -- there *is no* other way of preventing the default back button behavior other than overriding onBackPressed() – Droidman Sep 20 '17 at 15:10