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

블루투스 통신질문입니다.

0 추천

안녕하세요, 블루투스 활용한 앱을 개발하고 있습니다.

책도 찾아보고 무엇이 문제인지 며칠째 해결책을 찾아보고, 성공앱들에서

되는 부분 복붙도 해보았는데 도무지 해결방안을 찾지 못해 질문드립니다.

많은 도움 부탁드립니다!

 

public class Gateway {
     
    private static final String TAG = "Gateway";
    public static final String BLUETOOTH_LIST_KEY = "bluetooth_list_preference";
     
    private final static int MSG_END_LOGGING = 10;
     
    private static final UUID MY_UUID = UUID.fromString
("00001101-0000-1000-8000-00805F9B34FB");
    private static final int REQUEST_ENABLE_BT = 1;
     
    private Context mCtx;
    private MonitoringService mParent; 
     
    private BluetoothDevice mBTDev = null;
    private BluetoothSocket mBTSock = null;
    private BluetoothSocket mBTSockFallback = null;
     
    CommandRequestThread mCmdReqThread;
    MainHandler mMainHandler;
     
    boolean mOnLogging = false; //로깅 flag
    boolean mOnUiUpdate = false;//UI 업데이트 flag
     
    ArrayList<Command> mInterruptCmds = new ArrayList<Command>();  
     
    SharedPreferences prefs;
    // bluetooth variable
    final BluetoothAdapter btAdapter;
    /**
     * 인터페이스 연결
     * @param
     */
    GatewayListener mEventListner = null;
    public void setGatewayListener(GatewayListener EventListner){
        mEventListner = EventListner;
    }
     
    public static Gateway getInstance(MonitoringService context) {
        if(instance == null) {
            instance = new Gateway(context);
        }
         
        return instance;
    }
     
    public static void destroyInstance(){
        instance = null;
    }
     
    private Gateway(MonitoringService service) {
        mCtx = service;
        mParent = service;
         
        prefs = PreferenceManager.getDefaultSharedPreferences(mCtx);
        mCmdReqThread = new CommandRequestThread();
        mMainHandler = new MainHandler();
         
         
        btAdapter = BluetoothAdapter.getDefaultAdapter();
         
        initAnalyzer();
    }
         
protected void startConnection() {
        // turn on & check the Bluetooth adapter
if(btAdapter != null) {  //장치가 블루투스를 지원하는 경우
if(!btAdapter.isEnabled()) {
if(btAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF ||
        btAdapter.getState() == BluetoothAdapter.STATE_OFF) {               btAdapter.enable();
                }
            }
        }
             
        if(btAdapter != null && btAdapter.isEnabled()){
        // get the remote Bluetooth device     
//final String remoteDevice = prefs.getString(BLUETOOTH_LIST_KEY, null);
       final String remoteDevice = Application.getAppData(BLUETOOTH_LIST_KEY);
    if (remoteDevice == null || "".equals(remoteDevice)) {
Toast.makeText(mCtx, "No Bluetooth device selected", Toast.LENGTH_LONG).show();
    Log.e(TAG, "No Bluetooth device has been selected.");
            }
            else {
    //final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        mBTDev = btAdapter.getRemoteDevice(remoteDevice);          
        btAdapter.cancelDiscovery();
        startBTConnection();
            }
        }
        else{
             
        Toast.makeText(mCtx, "Bluetooth is not enabled", Toast.LENGTH_LONG).show();                
        }
    }
     
     * @throws IOException
     */
    private void startBTConnection() {
    Log.d(TAG, "Starting Bluetooth connection..");
             
    try {
    // Instantiate a BluetoothSocket for the remote device and connect it.
    mBTSock = mBTDev.createRfcommSocketToServiceRecord(MY_UUID);
    Log.e(TAG, "..");
 
    mBTSock.connect(); //breakpoint
        } catch (Exception e1) {
    Log.e(TAG, "There was an error while establishing Bluetooth connection. Falling back..", e1);
             
    //hidden method for bluetooth socket
    Class<?> clazz = mBTSock.getRemoteDevice().getClass();
    Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
    try {
        Method m = clazz.getMethod("createRfcommSocket", paramTypes);
        Object[] params = new Object[]{Integer.valueOf(1)};
mBTSockFallback = (BluetoothSocket) m.invoke(mBTSock.getRemoteDevice(), params);
        mBTSockFallback.connect();
        mBTSock = mBTSockFallback;
        } catch (Exception e2) {
Log.e(TAG, "Couldn't fallback while establishing Bluetooth connection. Stopping app..", e2);
            }
        }
    }
     
    protected boolean isConnected(){
        boolean isConnected = false;
        if(mBTSock != null) {
            isConnected = mBTSock.isConnected();
        }
         
        return isConnected;
    }
     
    protected boolean isPrepared(){
        return mIsPrepared;
    }
     
    protected String getMacAddress(){      
        String mac = null;
        if(mBTDev != null){
            mac = mBTDev.getAddress();
        }
         
        return mac;
    }
     
         
    protected void stopConnection() {
    mCmdReqThread.interrupt();//TODO 중단이 잘 안되는 거 같은데..? --> 안드로이드 메모리 관리자 맘대로임
    mCmdReqThreadRunning = false;//SOLVE flag 사용법으로 하는게 확실
    mIsPrepared = false;
     
    if (mBTSock != null){
        // close socket
    try {
        mBTSock.close();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
        }
         
        // bluetooth turn-off
//      if(btAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON ||
//              btAdapter.getState() == BluetoothAdapter.STATE_ON)
//          btAdapter.disable();
    }
     
    /**
 */
    protected void startLogging(){
        mOnLogging = true;
        initAnalyzer();
    }
     
    protected void stopLogging(){
        mOnLogging = false;
    }
     
    protected boolean isOnLogging(){
        return mOnLogging;
    }
     
    /**
     *
     */
    protected void troubleshooting () {
         
    }
   
    /**
     * 명령어 실행
    */
    private HashMap<String, String> executeCommand(ArrayList<Command> cmds){
        HashMap<String, String> commandResults = null;
        if(cmds != null) {
            commandResults = new HashMap<String, String>();
            int countCmds = cmds.size();
            int countError = 0;
            for(int i = 0; i < countCmds; i++) {
                Command cmd = cmds.get(i);
                boolean isError = false;
                 
                try{
            Log.d(TAG, "Command starts to run..");
            isError = false;
            cmd.run(mBTSock.getInputStream(), mBTSock.getOutputStream());
            } catch(Exception e) {
            isError = true;                
            Log.e(TAG, "Failed to run command. -> " + cmd.getName() + " -> " + e.getMessage());
                }
                 
                String cmdName = cmd.getName();
                String cmdResult = "";
//              String cmdId = Utils.LookUpCommandId(cmdName); 
                if(isError) {
//                  cmdResult = cmd.getResult();
                    cmdResult = "";
                    countError++;
/*
                }
                else{
                    cmdResult = cmd.getFormattedResult();
                }
                 
//Log.e(TAG, "Read complete!!");/*
* UI 업데이트
*/

 

zitrocy (120 포인트) 님이 2016년 8월 17일 질문

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...