How to crash an Android app programmatically?

后端 未结 13 1519
遥遥无期
遥遥无期 2021-02-05 00:37

I want to test out crash report using acra but the first step is I need to simulate a fatal crash in Android using code.

Any idea?

13条回答
  •  名媛妹妹
    2021-02-05 00:43

    in addition to @vinnet-shukla answer:

    "OR simply throw an uncaught exception"

    throwing uncaught exception to do a crash is bad idea as the exception could by caught somwhere higher in the stack - especially when whe don't know where we are right now :)

    more ellegant way is to use ERROR

    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

    so we could make our own Error subclass and use it:

    /*
     * usage:
     * 
     *   CrashError.doCrash(); 
     *
     */
    public class CrashError extends Error {
    
        public CrashError() { 
            this("simulated crash");
        }
    
        public CrashError(String msg) {
            super(msg);
        }
    
        public static void doCrash() {
            throw new CrashError();
        }
    
    }
    

    but if we talk about other possibilities we could also a throw checked exception :)

    this will also be a lesson how we could RETHROW CHECKED EXCEPTION :) with other way than use of sun.misc.Unsafe especially when the class is not available in VM implementation

    @SuppressWarnings("unchecked")
    public static  void throwAnyT(Throwable e) throws E {
        throw (E) e;
    }
    
    public static void throwUnchecked(Throwable e) {
        throwAny(e);
        // should never get there.
        throw new InternalError();
    }
    
    public static void crash() {
        throwUnchecked(new java.io.IOException("simulated crash"));
    }
    

    in addition to @audric answer:

    "You can't throw null"

    yes you can :) it's exactly what you are doing in your example and yes it could get undetectable if the catch block will not use Throwable - the NPX will never be thrown and simply there will be normal flow when code will still execute and yes i'll have seen this and experienced by myself :) on ANDROID DALVIK

    and what about..? maybe it could fulfill your needs?

    java specific (also in android):

    - Runtime.getRuntime().exit(int);
    - System.exit(int);
    - Runtime.getRuntime().halt(int);
    

    android specific:

    - android.os.Process.killProcess(int);
    - android.os.Process.killProcessQuiet(int);
    - android.os.Process.sendSignal(int,int);
    - android.system.Os.kill(int);
    

提交回复
热议问题