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

블루투스를 이용하여 PC에 데이터를 보낼려고하는데요.

0 추천
package com.example.ledonoff;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LEDOnOff extends Activity {
  private static final String TAG = "LEDOnOff";
  
  Button btnMove1, btnMove2;
  
  private static final int REQUEST_ENABLE_BT = 1;
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private OutputStream outStream = null;
  
  // Well known SPP UUID
  private static final UUID MY_UUID =
      UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // Insert your bluetooth devices MAC address
  private static String address = "20:13:02:21:00:73";
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    setContentView(R.layout.activity_main);

    btnMove1 = (Button) findViewById(R.id.move1);
    btnMove2 = (Button) findViewById(R.id.move2);
    
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

    btnMove1.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("A");
      }
    });

    btnMove2.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("B");
      }
    });
  }
  
	public static String stringToHex(String str){
		String result = "";
		for(int i=0; i<str.length(); i++){
			result += String.format("%02X", (int)str.charAt(i));
		}
		return result;
		
	}
	
  @Override
  public void onResume() {
    super.onResume();

    Log.d(TAG, "...In onResume - Attempting client 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 = device.createRfcommSocketToServiceRecord(MY_UUID);
    } 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 to Remote...");
    try {
      btSocket.connect();
      Log.d(TAG, "...Connection established and data link opened...");
    } 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, "...Creating Socket...");

    try {
    	
      outStream = btSocket.getOutputStream();
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }
  }

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

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

    if (outStream != null) {
      try {
        outStream.flush();
      } catch (IOException e) {
        errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
      }
    }

    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 supported. Aborting.");
    } else {
      if (btAdapter.isEnabled()) {
        Log.d(TAG, "...Bluetooth is enabled...");
      } else {
        //Prompt user to turn on Bluetooth
        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    }
  }

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

  private void sendData(String message) {
//	  message = stringToHex(message);
	  byte[] msgBuffer = null;
	  try {
		String str = new String(message.getBytes(),"UTF-8");
		msgBuffer = str.getBytes();
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
    Log.d(TAG, "...Sending data: " + message + "...");

    try {
      outStream.write(msgBuffer);
    } catch (IOException e) {
      String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
      if (address.equals("20:13:02:21:00:73")) 
        msg = msg + ".\n\nUpdate your server address from 20:13:02:21:00:73 to the correct address on line 37 in the java code";
      msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
      
      errorExit("Fatal Error", msg);       
    }
  }
}

Docklight를 이용하여 데이터가 넘어오는건 확인이 되는데 

넘어온 데이터값이 깨져서 넘어옵니다... baud랑 페러티랑 다 맞추고 하는데도 그렇네요...

무엇이 문제 인지 잘모르겠습니다ㅠㅠㅠㅠㅠ

A 를 넘기면 Hex값이 41이 넘어와야되는데 자꾸 깨져서 이상한 값이 넘어옵니다...

초보초보초보개발 (840 포인트) 님이 2014년 9월 5일 질문

1개의 답변

0 추천
//String str = new String(message.getByte(), "UTF-8");

이줄 주석하시구

msgBuffer = message.getByte("US-ASCII");

해서 해보세요
익명사용자 님이 2014년 9월 5일 답변
바우드값을...이것저것 다바꾸면서 해봤더니..
해결됐습니다..ㅠㅠ 신경써주셔서 감사합니다.
답변으로 해결됐으면 채택을 하세요.
...