简体   繁体   English

android:如何从服务到活动回调?

[英]android:How to get call backs from service to activity?

I am using a service to upload a file to server and I am getting some result after file uploaded I want some call backs from service like when upload completed, when got result, if didn't got result in specific time, when network lost etc. as per these call backs I need changes in my activity from where my service was called. 我正在使用服务将文件上传到服务器,我在上传文件后得到一些结果我想要一些来自服务的回调,比如上传完成,得到结果,如果没有得到结果在特定时间,网络丢失等根据这些回调,我需要更改我的活动,从我的服务被调用。 currently I am using different-different broadcast send and receive like this. 目前我正在使用不同的广播发送和接收这样的。

Intent w = new Intent("<KEY>");
w.putExtra("***", ***);
sendBroadcast(w);

It is working fine now but I want to know that it is proper way to do such or is there any better way? 它现在工作正常,但我想知道这是正确的方法,还是有更好的方法? I also red about pass Handler from activity and pass message queue from service but I am not comfortable this. 我也是红色关于从活动传递Handler并从服务传递消息队列但我不舒服这个。

Using BroadcastReceivers is perfectly fine. 使用BroadcastReceivers非常好。 But if your worker upload-thread needs to run once-off time, then an AsyncTask may better suits your needs. 但是如果你的工作者上传线程需要一次性运行,那么AsyncTask可能更适合你的需求。 You do your work in doInBackground and then use onPostExecution() to update your GUI. 你在doInBackground工作,然后使用onPostExecution()来更新你的GUI。

As you said, you can also use a Handler inside your Activity. 如您所说,您还可以在Activity中使用Handler。 But then your Service will need to be a bound Service in order for you to be able to pass the Handler to the Service. 但是,您的服务将需要成为绑定服务,以便您能够将处理程序传递给服务。

For very simple things, I'd advise you to use an AsyncTask. 对于非常简单的事情,我建议你使用AsyncTask。

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

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