应用程序在传输数据时没有响应

时间:2014-04-12 10:13:51

标签: android sockets android-asynctask ui-thread

我使用套接字服务器和客户端发送图像。它给了我对话框"应用程序无响应"我认为转换这个位图是因为在UiThread中进行了转换。所以我试图改变它,但我仍然得到这个消息"应用程序没有响应"。当我发送大图像+ 500kb时,它正在发生。

这是我的服务器代码:

public class SocketServerThread extends Thread {

      static final int SocketServerPORT = 8080;
      int count = 0;

      @Override
      public void run() {
       try {
        serverSocket = new ServerSocket(SocketServerPORT);               
        while (true) {
         Socket socket = serverSocket.accept();
         count++;

         // Here where i am doing my code i think is not doing in UiThread..

         MainActivity.this.runOnUiThread(new Runnable() {
          @Override
          public void run() 
          {                 
          // Firstly i was doing my code here...
          }
         });

        }
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }

     }

我的客户代码:

public class MyClientTask extends AsyncTask<Void, Void, Void> {   

      MyClientTask(String addr, int port){
       dstAddress = addr;
       dstPort = port;
      }

    @Override
    protected Void doInBackground(Void... arg0) {

           Socket socket = null;

           try 
                        {
    //I am sending my image here... 

            }
        }
           } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
           } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
           }finally{
            if(socket != null){
             try {
              socket.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
           return null;
          }
          @Override
          protected void onPostExecute(Void result) 
          {
           super.onPostExecute(result);
          }
    }

所以请帮助我。为什么我还没有回应对话?

1 个答案:

答案 0 :(得分:0)

当您阻止UI线程超过5秒时,会发生ANR错误代码。如果你需要做后台工作,请不要使用主线程。在单独的线程中接收数据,并将结果发布到UI线程。