[英]how to make a Service and AsyncTask communicate
I have this issue: I have a main activity that is bound to a service, Also, that main activity can call a class (AsyncTask) that is a client that connects to a server and waits for data. 我有这个问题:我有一个绑定到服务的主活动,而且,该主活动可以调用一个类(AsyncTask),该类是连接到服务器并等待数据的客户端。
I tried to make the bind from class (AsyncTask) client to the service, but I don't know if that's possible or do I have to return data to the main activity so main activity can send it to the service? 我试图将类(AsyncTask)客户端与服务进行绑定,但是我不知道这是否可行,还是我必须将数据返回给main活动,以便main活动可以将其发送到服务?
I can do this in the main class 我可以在班上做
Intent intent = new Intent(getApplication(), ChatHeadService.class);
startService(intent);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
but how can I implement it in the class (AsyncTask) client? 但是如何在类(AsyncTask)客户端中实现它?
You can return the data from your async task to the main activity this way. 您可以通过这种方式将数据从异步任务返回到主要活动。
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
Then you can pass that data from activity to service by calling startService(...)
and passing data in an intent
. 然后,您可以通过调用
startService(...)
并将数据以intent
传递,从而将数据从活动传递到服务。
Calling startService(...)
multiple times is safe and will not start multiple instances. 多次调用
startService(...)
是安全的,并且不会启动多个实例。
PS Running a server in Android doesn't sound right to me. PS在Android上运行服务器听起来不对。 Android devices should only be used as clients.
Android设备只能用作客户端。
I think that you can just invoke the service from doInBackground()
like you can in the activity. 我认为您可以像在活动中一样从
doInBackground()
调用服务。 See this Stack Overflow post for a solution to a similar problem. 有关类似问题的解决方案,请参见此Stack Overflow帖子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.