Search code examples
javaandroidsocketsbufferedreaderprintwriter

How to leave the program successfully


Today I write a program.It works successfully and is almost finished.But I found when I close the Socket,BufferedReaderandPrintWriter,the program always shows ANR.I feel confused about that.Is there any sequence to close the program??

@Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            try {
                mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
                mPrintWriter.close();
                mBufferedReader.close();
                mSocket.close();
                net_.interrupt(); //This is the thread to send and receive data.
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

This is my question and I want to eliminate this bug to keep my program perfect.Thanks


Solution

  • Read this Android - how do I investigate an ANR?

    And maybe try something like that

        @Override
        public void onClick(DialogInterface dialog, int which) {
    
          thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
                } catch (IOException e) {
                    e.printStackTrace();
                } finally{
                    mPrintWriter.close();
                    mBufferedReader.close();
                }
    
                try{
                    net_.interrupt();
                }catch (IOException e) {
                     e.printStackTrace();
                }finally{
                    mSocket.close();
                }
            }
         });
    
         thread .start();
        }
    

    And at the end of your app you should join that thread

       thread.join();