如何完全重新启动应用程序?重新启动、应用程序

2023-09-12 05:13:28 作者:TFBOYS照亮我的心

我有开始在其首次推出的活动远程服务的应用程序。然后,在另一个活动中,用户可以设置应用程序的配置。请注意,本次活动是没有绑定的服务,我不希望绑定。

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 note that this second activity isn't bound to the Service and I don't wish to bind it.

现在我的问题是:我怎么可能重新从第二个活动的整个应用程序,更改配置设置后

Now my question is : how could I restart the whole application from the second activity, after changing the configuration settings?

现在,我使用的是按钮,onClickListener是:

For now, I am using a button which onClickListener is :

public void onClick(DialogInterface dialog, int which) {
    sauvegarde();
    Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
}

的问题是:它只是重启的当前活动,而无需关闭整个应用程序,因此,在不重新启动该服务

The problem is : it only restarts the current activity without shutting the whole application, and therefore, without restarting the service

任何想法?

推荐答案

您可以使用机器人系统的AlarmManager像这样的:

You can use the Androids system AlarmManager like this:

code,以重新启动您的活动应用程序:

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);

这是例子可以抬起头来here

更新

由于@CommonsWare指出,它的一个坏的方式来设计你的应用程序,当你不得不重新启动它(糟糕的做法)。如果你真的想这样做,你可以尝试设置alarmmanager启动您的应用程序在第二个你杀了自己的过程后:

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());