Android 退出 AsyncTask
我有一个 AsyncTask 正在运行一个循环,该循环仅在退出应用程序时停止循环,设置全局“停止”布尔值,它会停止循环并完成 AsyncTask。
我有这段代码:
@Override
public void onBackPressed()
{
KillAllThreads();
}
@Override
public void onUserLeaveHint()
{
KillAllThreads();
}
现在事情是这样的。如果我启动 AsyncTask,onUserLeaveHint() 会立即被调用,并且当按下主页按钮时,它永远不会触发此方法。如果我不启动 AsyncTask 并让 Activity 加载而不执行任何操作,那么当我按 Home 时,它会触发 onUserLeaveHint() 方法。
如果用户点击退出应用程序,我该如何停止线程?
I have an AsyncTask running a loop which only stops looping when exiting the app, a global "stop" boolean gets set and it stops the loop and finishes through the AsyncTask.
I have this code:
@Override
public void onBackPressed()
{
KillAllThreads();
}
@Override
public void onUserLeaveHint()
{
KillAllThreads();
}
Now here is the thing. If I initiate the AsyncTask, onUserLeaveHint() gets called right away, and when the home button is pressed, it never fires this method. If I dont initiate the AsyncTask and let the activity load without doing anything, then when I press Home, it fires the onUserLeaveHint() method.
How am I supposed to stop the thread if the user clicks out of the app?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够在 AsyncTask 上调用 .cancel() ,您尝试过吗?
看看我的谷歌文档上的这个示例项目,它说明了 AsyncTask 的重要方面:
链接:
https://docs.google.com/leaf?id=0BwAnjRVwT4WzOWMwYjFhNTctOTUxYy00NjQwLTgwNWEtMmE5MzEyZWQ3NjUx&hl=en_US&authkey=CLnH8_ID
You should be able to call .cancel() on a AsyncTask, have you tried that?
Have a look at this sample project on my google docs, It illustrates the important aspects of AsyncTask:
link:
https://docs.google.com/leaf?id=0BwAnjRVwT4WzOWMwYjFhNTctOTUxYy00NjQwLTgwNWEtMmE5MzEyZWQ3NjUx&hl=en_US&authkey=CLnH8_ID