我有一个关于 android 生命周期的问题。这是我的主应用程序的onCreate方法:
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
decode = new Decode(this);
adjustToDimensions();
setLoadingScreen("Zorgdossier wordt geladen...");
initReceiver();
startCommunicationWithServer();
}
我将屏幕设置为加载屏幕,初始化广播接收器并向服务器发送消息。
现在,当我按下主页按钮并再次启动我的应用程序时,我总是想启动这个活动,所以我添加了
android:clearTaskOnLaunch="true"
到清单。
但是现在我希望在用户再次启动应用程序时执行startCommunicationWithServer ()。此方法向服务器发送一条消息,另一方面,服务器发送一条我在接收器中收到的消息。通过此消息,我决定显示哪个屏幕。
我试图把它放在onRestart方法中:
@Override
protected void onRestart() {
Log.d("MainActivity", "activity restarted");
startCommunicationWithServer();
super.onRestart();
}
但是这个活动在整个应用程序中会显示多次,所以每次都会执行 onRestart 方法。但我只需要在应用程序启动时执行startCommunicationWithServer ()。
长话短说,当用户退出并随后启动我的应用程序时,如何调用startCommunicationWithServer () 方法?