如何使用Thread进行neworking操作

时间:2015-11-06 09:38:59

标签: android multithreading

我有这个功能,它做网络操作..(即将数据发布到网页)..但我得到android.os.NetworkOnMainThreadException .. 我明白我必须在线程上使用网络操作,但我不知道如何做到这一点......你们可以帮助我解决我的代码问题。 提前致谢..... 这是我的方法

#-&

2 个答案:

答案 0 :(得分:0)

使用线程或Asynctask

调用asynctask

  new TheTask().execute("http://192.168.1.88/androidtesting.php");

的AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

class TheTask extends AsyncTask<String,String,String>
    {

@Override
protected String onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    // update textview here
    textView.setText("Server message is "+result);
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
     try
        {
           excutePost(String targetURL, String urlParameters);
         }
         catch(Exception e){
             return "Network problem";
         }

}
}

答案 1 :(得分:0)

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //this method will be running on UI thread
    pdLoading.setMessage("\tLoading...");
    pdLoading.show();
}
@Override
protected Void doInBackground(Void... params) {

    //this method will be running on background thread so don't update UI      
      frome here
    //do your long running http tasks here,you dont want to pass argument 
    //and u can access the parent class' variable url over here
    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    //this method will be running on UI thread

    pdLoading.dismiss();
}

}
}

并在oncreate()中将其称为 -

new AsyncCaller().execute();