마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

error data send: socket closed 안드로이드 스튜디오

0 추천
public class MainActivity extends Activity {
    private static final String TAG = "bluetooth2";

    Button btnLed1, btnLed2, btnLed3, btnpado;
    TextView txtArduino;
    RelativeLayout rlayout;
    Handler h;

    final int RECIEVE_MESSAGE = 1;        // Status  for Handler
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder sb = new StringBuilder();
    private static int flag = 0;

    private ConnectedThread mConnectedThread;

    // SPP UUID service
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "98:D3:61:FD:59:9D";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnLed1 = (Button) findViewById(R.id.btnLed1);
        btnLed2 = (Button) findViewById(R.id.btnLed2);


        txtArduino = (TextView) findViewById(R.id.txtArduino);
        rlayout = (RelativeLayout) findViewById(R.id.layout);
        h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);
                        sb.append(strIncom);
                        int endOfLineIndex = sb.indexOf("\r\n");
                        if (endOfLineIndex > 0) {
                            String sbprint = sb.substring(0, endOfLineIndex);
                            sb.delete(0, sb.length());
                            txtArduino.setText("Data from Arduino: " + sbprint);
                           
                        break;
                }
            };
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();

        btnLed1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mConnectedThread.write("1");
                //Toast.makeText(getBaseContext(), "Turn on First LED", Toast.LENGTH_SHORT).show();
            }
        });
        btnLed2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mConnectedThread.write("2");
                //Toast.makeText(getBaseContext(), "Turn on Second LED", Toast.LENGTH_SHORT).show();
            }
        });
        
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - try connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting...");
        try {
            btSocket.connect();
            Log.d(TAG, "....Connection ok...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    }

    @Override
    public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            errorExit("Fatal Error", "Bluetooth not support");
        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    private void errorExit(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    }

 

 

D/ViewRootImpl@1db829d[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl@1db829d[MainActivity]: ViewPostIme pointer 1
D/bluetooth2: ...Data to send: 2...
    ...Error data send: socket closed...
D/InputMethodManager: prepareNavigationBarInfo() DecorView@a62bffa[MainActivity]
    getNavigationBarColor() -855310
V/InputMethodManager: Starting input: tba=com.example.yj.bluetoothapplication ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager: startInputInner - Id : 0
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport: Input channel constructed: fd=73
D/InputTransport: Input channel destroyed: fd=70
D/bluetooth2: ...In onPause()...
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@48bbe5, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@55f6ba, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@3a2e96bmSocket: null, mSocketState: CLOSED
D/ViewRootImpl@1db829d[MainActivity]: setWindowStopped(true) old=false
D/ViewRootImpl@1db829d[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1
D/InputMethodManager: prepareNavigationBarInfo() DecorView@a62bffa[MainActivity]
    getNavigationBarColor() -855310
W/libEGL: EGLNativeWindowType 0x7d358f9010 disconnect failed
D/OpenGLRenderer: eglDestroySurface = 0x7d1bf9f180, 0x7d358f9000
D/ViewRootImpl@1db829d[MainActivity]: Relayout returned: old=[0,0][1080,2280] new=[0,0][1080,2280] result=0x5 surface={valid=false 0} changed=true

 

 

 

https://github.com/ujink/Android-HC06-Arduino 이 코드입니다. 

해결 방법 아시나요?

 

gs25 님이 2019년 9월 21일 질문

1개의 답변

0 추천

앞의 로그가 어떻게 되었는지는 몰라도, 

2번 버튼 눌러 2라는 데이터 전송시 소켓이 close되었다고 전송 오류 찍 혔네요..

 

아무래도 블루투스 연결이 제대로 안된 것으로 생각되는데, Connection ok 라는 문구가 출력 된건가요?

안되었다면, 하드 코딩된 블루투스 주소를 단말에 맞춰 보시고

마쉬멜로 이상 단말이라면, 아래 주소를 참조해서  runtime permison 을 획득하게 해서,   다시 시도 해 보세요.

https://stackoverflow.com/questions/36784663/requesting-multiple-bluetooth-permissions-in-android-marshmallow

 

 Connection ok 가 출력되었는데도 안된다면, 무슨 이유인지는 몰라도,  close가 불린 거니 close를 부르는 쪽에 로그를 넣어 어디서 close를 부르는지 확인 해 보시는게 좋을 듯 합니다.

익명사용자 님이 2019년 9월 23일 답변
...