简体   繁体   English

Android:何时取消注册侦听器 - onStop()或onDestroy()

[英]Android : when to unregister the listener - onStop() or onDestroy()

I have basic question regarding when to unregisterListener for sensor manager. 我有关于何时unregisterListener传感器管理器的unregisterListener基本问题。 Should it be done in onStop() or onDestroy() . 应该在onStop()还是onDestroy()

Usecase : 用例:

I want to record accelorometer on click of start button and stop when user clicks stop button. 我想点击开始按钮记录accelorometer ,当用户点击停止按钮时停止。 the frequency of data is every minute. 数据的频率是每分钟。 So I have started a timer . 所以我已经启动了timer

But the issue is every time the orientation changes as per Android architecture, onStop() gets called. 但问题是每次根据Android架构改变orientation ,都会调用onStop() In onStop() I am cancelling the timer and unregistering the listener. onStop()我取消了计时器并取消注册了监听器。

SO again if I start timer/register listener in onResume() the frequency won't remain 1 minute and also the data gets recorded without user pressing the start button. 再次如果我在onResume()启动定时器/寄存器监听器,频率将不会保持1分钟,并且在没有用户按下开始按钮的情况下记录数据。

Can someone help me resolve this issue. 有人可以帮我解决这个问题。

Thanks. 谢谢。

You may want to use a Service to run the accelerometer data collecting in the background, communicating with it using basic intents is not too complicated. 您可能希望使用Service来运行在后台收集的加速计数据,使用基本意图与其进行通信并不太复杂。

Or, if you only want to 'survive' the rotation, when the activity gets destoryed and then rebuilt, try overriding in your Activity the onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() methods (read more about it here ) 或者,如果您只想“保持”旋转,当活动被破坏然后重建时,请尝试在您的Activity覆盖onRetainNonConfigurationInstance()getLastNonConfigurationInstance()方法( 在此处阅读更多相关信息)

OnDestroy() isn't guaranteed to be called. 不保证调用OnDestroy() So you should do it in either onPause or onStop 所以你应该在onPauseonStop

But the issue is every time the orientation changes as per Android architecture 但问题是每次Android架构都会改变方向

There's a way to prevent this from happening in the manifest. 有一种方法可以防止在清单中发生这种情况。 I'm sure someone else will post how. 我相信其他人会发布如何发布。

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

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