2016-08-09 2 views
-1

내가 handleMessage안드로이드 핸들러 handleMessage

+0

훨씬 쉽고 깨끗한 AsyncTasks를 사용해보십시오. –

+0

어쨌든 문제는'AsyncTask'에서'doInbackground'에서'onPictureTaken'을 사용하면'onPictureTaken'과 같은 에러가 나옵니다 – SimpleCoder

+0

logcat 로그를 공유 할 수 있습니까? –

답변

0

에서 메인 스레드 예외에 네트워크를 얻고있는 이유는 메인 스레드에서 그것에 작업에 핸들러의 인스턴스를 생성하기 때문에 누군가가 나에게 할 수 있습니다. 그리고 heandler에서는 소켓 연결 (인터넷 연결)을 주 스레드에서 만들려고합니다.

/** 
    * Default constructor associates this handler with the {@link Looper} for the 
    * current thread. 
    * 
    * If this thread does not have a looper, this handler won't be able to receive messages 
    * so an exception is thrown. 
    */ 
    public Handler() ; 
0

난 당신 때문에 Toast.makeText(getApplicationContext(), count, Toast.LENGTH_LONG).show();

에 예외를 발생하는 추측 새 스레드를 사용해보십시오 :

runOnUiThread(new Runnable() { 
    @Override 
    public void run() { 
     showToast(MessageBuilder.SUCCESSFUL_COMMENT); 
     } 
    }); 
0

당신은 백그라운드에서 핸들러를 실행해야합니다. 이 경우 Looper을 사용할 수 있습니다. https://developer.android.com/reference/android/os/Looper.html을 참조하십시오.

이 작업을 시도 할 수 :

Thread thread = new Thread() { 
     @Override 
     public void run() { 
      super.run(); 
      Looper.prepare(); 

      handler = new Handler() { 
       @Override 
       public void handleMessage(Message msg) { 
        super.handleMessage(msg); 
        try { 
         String tmp = msg.obj.toString(); 
         InetAddress serverAddr = InetAddress.getByName(serverIP); 
         socket = new Socket(serverAddr, serverPort); 
         OutputStream outStream = socket.getOutputStream(); 
         PrintWriter writer = new PrintWriter(outStream); 
         writer.write(tmp); 
         writer.flush(); 
         InputStream inStream = socket.getInputStream(); 
         byte[] xxx = new byte[20]; 
         int count = inStream.read(xxx); 
//   Toast.makeText(getApplicationContext(), count, Toast.LENGTH_LONG).show(); 

         outStream.flush(); 
         outStream.close(); 

        } catch (UnknownHostException e) { 
         e.printStackTrace(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } finally { 
         Looper.myLooper().quit(); 
        } 
       } 

      }; 
      handler.removeCallbacks(this); 
      Looper.loop(); 
     } 
    }; 

    thread.start(); 

은 또한 당신이 RuntimeError에 원인이됩니다 핸들러에 Toast을 보이고있다. 처리기에서 토스트를 꺼내십시오.

+0

오케이, 어떻게 생겼을 까? 내 코드에 따라 이걸 보여 주시겠습니까? – SimpleCoder

+0

나는 이걸 내 원에서 해결하려고 노력했지만, 항상 InputStream에 의한 '메인 스레드 예외에 대한 네트워크'가 있습니다. – SimpleCoder

+0

@SimpleCoder 응답을 업데이트했습니다. 확인하십시오. –

관련 문제