Search code examples
javaandroiddebuggingbreakpoints

How to create a breakpoint programmatically on Android


In C# I can write:

if(Debugger.IsAttached)
    Debugger.Break();

This has no effect when the program is not being debugged. When a debugger is attached, it behaves like a breakpoint that can never be turned off. How can I achieve similar effect on Android?

Or maybe I should not focus on breakpoints at all. What I really want is to have no consequence in regular use (a generic error message will be shown to the user), but have the source of error become obvious the moment a dev will start looking at it. I've tried assert, but it's a sub-project that's compiled to release flavor most of the time and I can't rely on someone remembering to switch it to debug.


Solution

  • I think that Debug.isDebuggerConnected() is what you are looking for. This will return true only if the app is started with debugger attached and false otherwise, no matter of build type or flavor. Unfortunately, I don't think that you can stop the execution programatically, but with the above instruction you should be able to display an error message or throw an exception. Personally, I'm thinking to something like this:

    if (Debug.isDebuggerConnected()) {
        // throw an exception for the developer with a detailed message
    } else {
        // show the general error message to the user with a dialog/toast    
    }