如何将 Asynctask 与套接字一起使用
我在使用我的应用程序时遇到问题。我正在使用 AsyncTask 类来执行后台操作,就像使用套接字一样。我相信它在背景中很好。
好吧,在我的应用程序中,我有一个 UDP 侦听器和一个 UDP 发送器,它们分别从服务器侦听和向服务器侦听任何类型的数据,并且我为它们创建了异步类。现在我希望通过单击按钮从我的主要活动中执行两个 AsyncTask 类,我能够做到这一点,并且我有一个停止按钮来停止执行,但是一旦我单击停止按钮,线程仍然保持运行,原因是,在调用AsyncTask的onCancelled()
之后,它调用postexecute()
,而在我的postexecute()
中,我是制作我的一个对象AsyncTask 类并调用执行,以便我的监听器和发送器保持运行,即 doinBackground() 始终保持调用自身,并且监听器和发送器继续工作。
我知道在 postexecute() 中创建 Asynctask 类的对象不是一个好主意,因为它将处于无限循环中,但是如果我能够取消我调用的停止按钮上的执行oncancelled()
,它可能对我有用。
请帮我解决这个问题。
I do have a problem working with my application. I am using AsyncTask class to perform my background operation as working with Sockets. I believe it is good in Background.
Well, in my application, I have a UDP listener and a UDP sender that are listening from and to a server respectively any sort of data, and I have made async classes for both of them. Now I want both the AsyncTask classes to be executed from my main activity on a button click, that I am able to do, and I have a stop button to stop the execution, but once I click on the stop button, the thread still keeps running, the reason is, after calling the onCancelled()
of AsyncTask, its calling postexecute()
and in my postexecute()
, I am making an object of my AsyncTask class and calling execute so that my listener and sender keeps running i.e. doinBackground()
always keeps calling itself and listener and sender keeps working.
I know that making an object of Asynctask class in postexecute()
is not a good idea because it will be in an infinite loop, but if I am able to cancel the execution on stop button where I am calling oncancelled()
, it may work for me.
Please help me with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的问题是,当你取消 asyncTask 时,你实际上只取消了活动中调用的最外层 asynckTask,但是当你递归地运行 asyncTask 的其他实例时,你必须将它们全部取消让整个事情停止。
为什么不从
doInBackground()
中删除代码并将其放入方法中,然后从doInBackground()
内部调用它,如下所示:I think that your problem is that when you cancel your asynkTask, you're actually canceling only the outer most asynckTask which was called in the activity but as you've run other instances of your asyncTask recursively, then you've to cancel them all to get the whole thing stopped.
why don't you remove your code from inside
doInBackground()
and put it inside a method and call it from inside thedoInBackground()
as follows: