简体   繁体   English

onBackPressed之后未调用onCreate的类的静态块

[英]Static blocks of classes not called onCreate after onBackPressed

In my app when onCreate occurs I call a static method of another class. 在我的应用中,当发生onCreate时,我调用了另一个类的静态方法。 Eg ClassName.method(). 例如ClassName.method()。 This second class contains a static block which is also executed when the method is called. 第二类包含一个静态块,该静态块在调用该方法时也会执行。 This is exactly what I want to happen. 这正是我想要发生的事情。

However when I press the back button and return to the app, onCreate is again called (back caused onDestroy to execute) and that other method is called but the static block is not. 但是,当我按下“后退”按钮并返回到应用程序时,再次调用了onCreate(返回导致onDestroy执行),并且调用了其他方法,但没有调用静态块。 This isn't the case when I manually close the app from running in the background (the swipe technique) and then reopen it. 当我手动关闭应用程序以使其在后台运行(刷卡技术)然后重新打开它时,情况并非如此。 In that particular case the static block is called. 在这种特定情况下,将调用静态块。

Why is the static block of the class not called when the app restarts after onBackPressed? 为什么在onBackPressed后重新启动应用程序时未调用该类的静态块?

Thank you. 谢谢。

Update: 更新:

It seems to me that the class is not removed from memory even after onDestroy when back is pressed. 在我看来,即使在按下on的onDestroy之后,也不会从内存中删除该类。 I was under the impression that everything would reinitialise when onCreate is called again. 我的印象是,再次调用onCreate时,所有内容都会重新初始化。 However this does not seem to be the case. 但是,事实并非如此。 Is there a way to remove the class on calling onDestroy? 有没有办法在调用onDestroy时删除该类?

As I understand your question, the static block is not executed because the class is already loaded. 据我了解您的问题,因为该类已经加载,所以不会执行静态块。

class StaticTest { 

     static {
         // This will be executed once only. When the class is loaded and initialized.
     }

     static String s = "Exactly like this actually";
}

But it would be better to see the relevant portion of your code. 但是最好查看代码的相关部分。

A static block in a class is called during the initialization of the class. 在类的初始化期间,将调用类中的静态块。 Since, a class is loaded (and initialized) only once, the static blocks in it are called only once. 由于一个类仅被加载(和初始化)一次,因此其中的静态块仅被调用一次。

May be you shouldn't be using the static block at all. 可能是您根本不应该使用静态块。 Just put the code in a static method and call it whenever you want. 只需将代码放入静态方法中,然后随时调用即可。

on backpress simply instantiate the class
or put it in constructor instead of static block

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM