服务中的AsyncTask - 矫枉过正?

时间:2012-07-06 07:35:34

标签: android

我目前正在做一些网络相关的事情,

public void postData() {

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.xx.xx.php");

try {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 

在asynctask中,我正在从服务执行。

我想知道的是,它是否足以直接在服务中运行网络方法?因为AFAIK它不会在UI线程上运行。

由于

2 个答案:

答案 0 :(得分:3)

IntentService有自己的线程,你不需要AsyncTask,但在UI线程上运行正常Service,你需要移动需要很长时间的操作到另一个线程(比如使用AsyncTask)。主UI线程上运行的Servicedocs

中说明

答案 1 :(得分:2)

来自documentation

服务不是一个单独的过程。 Service对象本身并不意味着它在自己的进程中运行;除非另有说明,否则它与其所属的应用程序运行的过程相同。

除非你使用IntentService

,否则不是一种矫枉过正