How to restart an application completely?

前端 未结 7 1604
长发绾君心
长发绾君心 2021-01-04 17:35

I have an application which starts a Remote Service in its first launched activity. Then, in another activity, the user can set the configuration of the application. Please

7条回答
  •  情深已故
    2021-01-04 18:19

    You can use the Androids system AlarmManager like this:

    Code to restart the app in your activity:

    AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this.getBaseContext(), 0, new    Intent(getIntent()), getIntent().getFlags()));
    System.exit(2);
    

    An example can be looked up here

    UPDATE

    As @CommonsWare pointed out, its a bad way to design your app, when you have to restart it (bad practice). If you really want to do it, you can try setting alarmmanager to start your app in a second after you killed your own process:

    AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this.getBaseContext(), 0, new    Intent(getIntent()), getIntent().getFlags()));
    android.os.Process.killProcess(android.os.Process.myPid());
    

提交回复
热议问题