How do I programmatically “restart” an Android app?

后端 未结 26 2299
小鲜肉
小鲜肉 2020-11-22 12:42

Firstly, I know that one should not really kill/restart an application on Android. In my use case, I want to factory-reset my application in a specific case where a server s

26条回答
  •  耶瑟儿~
    2020-11-22 13:18

    You can use startInstrumentation method of Activity. You need implement empty Instrumentation and pointed in manifest. After that you can call this method for restart your app. Like this:

    try {           
        InstrumentationInfo info = getPackageManager().queryInstrumentation(getPackageName(), 0).get(0);
        ComponentName component = new ComponentName(this, Class.forName(info.name));
        startInstrumentation(component, null, null);
    } catch (Throwable e) {             
        new RuntimeException("Failed restart with Instrumentation", e);
    }
    

    I get Instrumentation class name dynamically but you can hardcode it. Some like this:

    try {           
        startInstrumentation(new ComponentName(this, RebootInstrumentation.class), null, null); 
    } catch (Throwable e) {             
        new RuntimeException("Failed restart with Instrumentation", e);
    }
    

    Call startInstrumentation make reload of your app. Read description of this method. But it can be not safe if acting like kill app.

提交回复
热议问题