Using another thread for “networking” , in Android

♀尐吖头ヾ 提交于 2019-12-22 18:13:18

问题


I am developing an Android application and when it launches :

1) I make an HTTP Request to my server to send a small JSON file.

2) Open a webView to show a URL.

When the server is running properly there is absolutely no problem and everything goes smoothly.

HOWEVER , if for any reason the server is down , the HTTP request literally hangs and i need to wait till there is an HTTP timeOut which is around 30seconds till i actually see the webView with the URL loading.

I read that i shouldn't make any networking inside the UI thread and i should use another thread for that.

In BlackBerry , that i have already developed the application for , this is as simple as that :

new Thread(){
  public void run(){
    HttpConnection hc = 
            (HttpConnection)Connector.open("http://www.stackoverflow.com");
  }
}.start();

I just start a new thread and inside i make the requests and all the necessary networking. That way , even when my server is not reachable the webView is loaded immediately without making the user wait and sense that the app is actually hanging.

How could i do exactly the same in Android , easiest way possible ?


回答1:


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();



回答2:


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




回答3:


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         
    }

}


来源:https://stackoverflow.com/questions/16213020/using-another-thread-for-networking-in-android

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