简体   繁体   English

服务是在Android中发出HTTP请求的最佳方法

[英]Is services is the best way to make http request in android

Is services is the best way to make http request to php server in android? 服务是在android中向php服务器发出HTTP请求的最佳方法吗? I am currently using the AsycTask but it sometimes unfortunately stops the application so i am planning to use services. 我目前正在使用AsycTask,但有时它不幸地停止了该应用程序,因此我打算使用服务。

You have to have good reasons for using any of them. 您必须有充分的理由使用其中任何一个。 If you want to perform something in background while app is at sleep then surely service is the way to go. 如果您想在应用程序处于睡眠状态时在后台执行某些操作,那么一定要使用服务。 AsyncTask lifecycle is based on Activity lifecycle. AsyncTask生命周期基于Activity生命周期。 If Activity dies and you have some pending code inside your AsyncTask then it can cause a crash so cancelling AsyncTask before exiting the app is a good practice. 如果Activity死了,并且AsyncTask中有一些待处理的代码,则可能会导致崩溃,因此在退出应用程序之前取消AsyncTask是一个好习惯。

But my recommendation and the best way is here to use Google Volley Library for making http request. 但是,我的建议和最佳方法是使用Google Volley Library发出http请求。 It takes care of everything for you. 它为您照顾一切。 You can easily cancel the request in case of exiting the app. 在退出应用程序的情况下,您可以轻松取消请求。

Http request only can be done in a non-UI thread. Http request只能在非UI线程中完成。 Because it may cause ANR(Application Not Responding) and is forbidden in the main thread in Android. 因为它可能导致ANR(Application Not Responding)并且在Android的主线程中被禁止。 And for Service , it's run on main thread by default except you set android:process="thread-name" when you deploy it in AndroidManifest.xml . 对于Service ,它默认情况下在主线程上运行,除了在AndroidManifest.xml部署它时设置android:process="thread-name" So, If you want to handle with http request on your own codes, you must use AsyncTask , Handler or HandlerThread . 因此,如果要使用自己的代码处理http请求,则必须使用AsyncTaskHandlerHandlerThread But I recommend you to use Google Volley , android-async-http or okHttp . 但我建议您使用Google Volleyandroid-async-httpokHttp Because they are encapsulated well and easy to use and take care everything for you. 因为它们被很好地封装并且易于使用,并为您妥善保管一切。

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

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