Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 方法“;锁;套接字服务器启动时的整个屏幕_Android - Fatal编程技术网

Android 方法“;锁;套接字服务器启动时的整个屏幕

Android 方法“;锁;套接字服务器启动时的整个屏幕,android,Android,下面是实现socket服务器的receive方法,它可以完美地工作 private void Receive(){ log.info("Server started - waiting for the clients."); try { Boolean end = false; ServerSocket ss = new ServerSocket(12345); while(!end){

下面是实现socket服务器的receive方法,它可以完美地工作

    private void Receive(){ 
    log.info("Server started - waiting for the clients.");
     try {
         Boolean end = false;
         ServerSocket ss = new ServerSocket(12345);
         while(!end){
                 //Server is waiting for client here, if needed
                 Socket s = ss.accept();
                 BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                 PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
                 String st = input.readLine();

                JSONObject jsonObj;
                try {
                    jsonObj = new JSONObject(st);
                    long id = jsonObj.optLong("DeviceID", count.addAndGet(1) );
                    String name = jsonObj.toString();
                    table.put(id, name);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                 etResult.setText(st);
                 Log.d("Tcp Example", "From client: "+st);
                 output.println("Response from Sever: Connectivity ok");
                 s.close();
                 if (st != null ){ end = true; }
         }
    ss.close();


    } catch (UnknownHostException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    }   
}
唯一的问题是,当我点击按钮调用该方法时,套接字开始侦听并等待客户端消息。虽然没有发生,但应用程序仍然冻结,我尝试按下任何其他按钮,应用程序可能会崩溃

有人知道如何处理它,让套接字在“后台”监听而不锁定整个屏幕吗


谢谢

制作一个线程或异步任务,并在上面执行所有套接字函数。如果这是您很少做的事情,并且希望启动它并处理结果,请使用AsyncTask。如果这是您想要经常做的事情,并且不想同时运行多个工作线程,或者让多个工作线程排队,请使用线程