简体   繁体   English

活动可以调用自己的onPause(),onStop()吗?

[英]Can an Activity call its own onPause(), onStop()?

My app interfaces with a Bluetooth peripheral. 我的应用程序与蓝牙外围设备接口。 When the peripheral wants to shut down, can I clean up the app simply by calling my Activity's own onPause() and onStop() methods? 当外围设备要关闭时,是否可以仅通过调用Activity自己的onPause()onStop()方法来清理应用程序? Is the fact that they call the superclass's methods likely to cause any problems? 他们调用超类的方法是否可能引起任何问题?

The idea would be to call finish() after that. 这个想法是在那之后调用finish()

Technically, yes, you can. 从技术上讲,是的,您可以。 What you should be asking is "Should I"? 您应该问的是“我应该”吗? Which the answer is no. 答案是否定的。

Like you've mentioned, since they do call the superclass methods, there is some extra Android OS cleanup magic that happens. 就像您提到的那样,由于它们确实调用了超类方法,所以还会发生一些额外的Android OS清理魔术。 It may result in a successful case once in a while, but it's not guaranteed. 有时可能会导致成功案例,但不能保证。 There is a lot of things that happen in the backround that you don't want to fool with. 您不想混在幕后的事情很多。 Don't reinvent the wheel. 不要重新发明轮子。

If there is code that is ran within the onPause and onStop methods that you would like to use elsewhere, I would create a function called cleanupBluetooth and the onPause and onStop would call and anywhere else it needs to. 如果您想在其他地方使用onPauseonStop方法中运行的代码,我将创建一个名为cleanupBluetooth的函数,并且onPauseonStop将在需要的任何地方调用。

If you need to actually call the onPause and onStop methods because you need to stop and halt the activity, you can do that by calling finish() ( how to use finish() ). 如果由于需要停止和停止活动而需要实际调用onPauseonStop方法,则可以通过调用finish()如何使用finish() )来实现。 The finish() method will call the appropriate Android OS magic that's needed to be called. finish()方法将调用需要调用的适当的Android OS魔术。

You can call them manually, but you shouldn't let Android do it itself when it needs to. 您可以手动调用它们,但您不应在需要时让Android自己进行调用。 If you wish to call those activities, you are likely not really wanting the activity any more, so you can just call finish and then android will call the relevant methods based on the activities life cycle. 如果您想调用这些活动,则可能不再需要该活动,因此您可以调用finish,然后android将根据活动生命周期调用相关方法。

You can find more info about the activity life cycle by going here 您可以通过此处找到有关活动生命周期的更多信息

OnPause() is also a method in your activity and it will likely normal method. OnPause()也是您活动中的一种方法,很可能是正常方法。 It overrides method of activity and you can call it from anywhere in activity and from interface also. 它会覆盖活动方法,您可以在活动中的任何位置以及从界面中调用它。

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

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