我开发 iOS 应用程序已经有一段时间了,现在我已经转向 Android。我有一个要求,当 View 出现(onResume)时我必须启动计时器(在Android中思考,我需要使用处理程序)并在 View 消失(onPause)时使计时器无效(停止处理程序)。我能够创建可运行的处理程序,但无法停止它。 我的代码是:
protected void AutoRefresh() {
try{
handler.postDelayed(new Runnable() {
public void run() {
new LongOperation().execute("");
}
AutoRefresh();
}, 60000);
}
catch(Exception ex){
}
}
现在,当 View 消失时,如何停止这个处理程序线程。如果这不是在 android 中实现计时器的正确方法,请发表评论。
最佳答案
when view appears(onResume) and invalidate timer(stop handler) when view disappears(onPause). I am able to create runnable Handler but not able to stop it.
保留对您使用的Runnable
的引用:
private Runnable mRefresh = new Runnable() {
public void run() {
new LongOperation().execute("");
}
AutoRefresh();
}
//...
protected void AutoRefresh() {
handler.postDelayed(mRefresh, 60000);
}
并在onPause
中将其删除,如下所示:
handler.removeCallbacks(mRefresh);
请记住,这不会删除当前正在执行的Runnable
(如果有),因此在LongOperation
的onPostExecute
中您可能希望在刷新 UI 或与 Activity
进行任何其他交互之前检查 Activity
是否仍然可用。
Please also comment, if its not the right way to do timer implementation in android.
您似乎需要在一定的时间间隔执行一个操作,并且使用 Handler
是执行此操作的方法,我不认为计时器是您所需要的。
关于android - 当 View 出现时创建计时器(处理程序)并在 View 消失时停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038622/