Android development: Restart application programmatically

Here are two short code snippets that I used to restart my Android application programmatically.

First, I added the following code in the onCreate method of the activity I would like to restart and saved references to the activity and the restart-intent to static attributes:

[...]
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  [...]
  ACTIVITY = this;
  RESTART_INTENT = PendingIntent.getActivity(this.getBaseContext(), 0, new Intent(getIntent()), getIntent().getFlags());
  [...]
}

Second, I used the following code to restart the application:

AlarmManager mgr = (AlarmManager)ACTIVITY.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, RESTART_INTENT);
System.exit(2);

Comments

  1. sprin

    I have the following problem: I’m doing some tests on applications with robotium and i want to restart the application from within the test case. Below is the code I’m working on

    public testtest(){
    super(“it.esercizio141.esempiomenu”,EsempioMenuActivity.class);

    }

    public void setUp() throws Exception {
    solo = new Solo(getInstrumentation(), getActivity());
    }

    public void testFai() throws Exception {
    solo.pressMenuItem(0);
    solo.pressMenuItem(1);
    this.launchActivity();

    }
    Where can I go to write something in order to restart the application? Thank you very much

Leave a comment

Your email address will not be published. Required fields are marked *

*