Using another thread for “networking” , in Android

为君一笑 提交于 2019-12-06 04:40:29

Why not to use the same method as you use it for BlackBerry?

new Thread() {
  public void run() {
    new URL("http://www.stackoverflow.com").getContent();
  }
}.start();

Use AsyncTask, it's the simplest way to do that. For more details: http://developer.android.com/reference/android/os/AsyncTask.html

Adnan

In icecream sandwich and above you are not allowed to use any web cal in UI thread. However you may use threads, but best way proposed by android is to use Async task. A very simple example is as follow.

"AsyncTask < Parameters Type, Progress Value Type, Return Type >"

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

    @Override
    protected void onPreExecute() {
     // Runs on UI thread- Any code you wants 
     // to execute before web service call. Put it here.
     // Eg show progress dialog
    }
    @Override
    protected String doInBackground(String... params) {
      // Runs in background thread
        String result = //your web service request;         

         return result;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String resp) {

      // runs in UI thread - You may do what you want with response 
      // Eg Cancel progress dialog - Use result         
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!