계속해서 안드로이드 공부를 하고있는 학생입니다

그런데 아직 계속 공부하고싶은데 급속도로 지나가는 날짜때문에 다른 학생들과 취업을위해 프로젝트를 진행하는데

제가 맡은 부분이 안드로이드 .... 프로젝트내용은 홈네트워크프로그램인데요 안드로이드에서 버튼 클릭시 예를들어 0x01을 보내면

 

블루투스로 받아서 블루투스에서 받은값을 ATMEGA128로보내고  지그비로 동일한값을 넘겨줘서 메인 ATMEGA128에서

0x01값을 받아서 그에 해당하는 작동을하는 프로젝트내용인데요 거의다 해결했는데 블루투스부분은 도저히 혼자 짤수없어서 안드로이드

블루투스Chat프로그램을 참조하고 참조해서 결국엔 한 엑티비티에서 버튼 클릭시 0x01의 값을 보내도록 되었는데요

다른엑티비티B에도 버튼이있어서 다른 엑티비티B에서 버튼클릭시 0x02의 값을 보내려고 하는데 안되는 문제가 발생 해버렸네요 ㅠ.ㅠ

이것저것 참조했는데 일단은 보내는게 되는 .java파일 내용입니다

참조했던 Tank컨트롤하는 앱의 일부소스입니다..

package com.example.sendbluetooth;

import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements
TextToSpeech.OnInitListener, OnClickListener {
// Debugging
private static final String TAG = "MainController";
private static final boolean D = true;

// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;

// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";

// Name of the connected device
private String mConnectedDeviceName = null;

// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;

// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private TankConService mTankConService = null;

// Layout Views

private TextView mStatus;
private TextToSpeech mTts;

/** Called when the activity is first created. */
@Override
// 처음으로 시작되는 메소드
//메인 엑티비티 xml 레이아웃 참조
//전체 메인xml의 버튼들을 감싸고있는 테이블레이아웃
//뷰 그룹으로 참조 이름 tblbuttons

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setOnClickListener((ViewGroup)findViewById(R.id.tblButtons));


mStatus = (TextView) findViewById(R.id.txtStatus);
//텍스트뷰 txtStatus 참조
mTts = new TextToSpeech(this, this);
// Get local Bluetooth adapter

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//블루투스 상태를담을 변수 초기 null값에 블루투스의 어댑터 get의 값 넣는다.

// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
//만약 블루투스 상태가 null 즉 초기상태인가 그럼 밑의 토스트 메시지 띄우고 엑티비티종료
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}
}

@Override
//두번째 시작되는 메소드
public void onStart() {
super.onStart();
if (D) //만약 참일경우 즉 이 메소드가 실행되면
Log.e(TAG, "++ ON START ++");
// ON START 라는 로그값을 찍은뒤에

// If BT is not on, request that it be enabled.
// setupTankCon() will then be called during onActivityResult

if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mTankConService == null)
mTankConService = new TankConService(this, mHandler);
}

}

//핸드폰의 메뉴버튼 눌렀을때 옵션 설정 주는메소드..
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
//Res밑 menu의 activity_main.xml 에서 item을 설정한것을 인플레이트 즉 참조.
//메뉴버튼을 눌렀을시 activity_main.xml의 item내용의 메뉴가 보인다..
//들어가보면 그 메뉴item의 이름은 scan이다.

}
//위 메소드에서 만든 메뉴버튼의 item 클릭시 이벤트 처리 메소드
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//인자값의 아이디의 가져온 Id가 scan인가 그렇다면 ..인텐트
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
//DeviceListActivity로 이동한다 요청코드 상수값 1을가지고이동.
}
return false;
}

//요청코드 보낸 인텐트의대한 처리 메소드..
//위에서부터 지금까지 온 요청코드는 두개 onSTART메소드에서한번
//바로위의 onOprionItemSelected메소드에서 한번 두가지 요청코드에 대한 답변 extra값 return

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "onActivityResult " + resultCode);
//로그 이메소드에 들어왔다면 로그값 onActivityResult 띄운뒤에 resultCode
//즉 요청코드값이 무엇인지 띄우고..

switch (requestCode) {
//만약 요청코드가
//옵션 셀렉 코드일때

case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras().getString(
DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mTankConService.connect(device);
}
break;
//만약 요청코드가 ONSTART메소드의 코드일때
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
if (mTankConService == null)
mTankConService = new TankConService(this, mHandler);
//만약 요청이 잘되었다면 mHandler이동 아닐경우 밑의 로그값과 토스트메시지보내기
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
}
}
}

//TTS를 사용하기위한 인터페이스 구현
//TTS란 메시지를 핸드폰에서 읽어주는 기능 ..
// Implements TextToSpeech.OnInitListener.

public void onInit(int status) {
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS) {
// Set preferred language to US english.
// Note that a language may not be available, and the result will
// indicate this.

int result = mTts.setLanguage(Locale.KOREAN);
// Try this someday for some interesting results.
// int result mTts.setLanguage(Locale.FRANCE);

if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Lanuage data is missing or the language is not supported.
Log.e(TAG, "Language is not available.");
} else {
// Check the documentation for other possible result codes.
// For example, the language may be available for the locale,
// but not for the specified country and variant.

// The TTS engine has been successfully initialized.
// Allow the user to press the button for the app to speak
// again.
// mAgainButton.setEnabled(true);
// Greet the user.


}
} else {
// Initialization failed.
Log.e(TAG, "Could not initialize TextToSpeech.");
}
}

private View[] getChildViews(ViewGroup group) {
int childCount = group.getChildCount();
final View[] childViews = new View[childCount];
for (int index = 0; index < childCount; index++) {
childViews[index] = group.getChildAt(index);
}
return childViews;
}

private void setOnClickListener(ViewGroup group) {
View[] childViews = getChildViews(group);
for (View view : childViews) {
if (view instanceof Button) {
view.setOnClickListener(this);
// ViewGroup일경우는 재귀호출 한다!
} else if (view instanceof ViewGroup) {
setOnClickListener((ViewGroup) view);
}
}
}
public void onClick(View v) {
if (v instanceof Button) {
if (v.getId() == R.id.btnF){
Intent intent = new Intent(getApplicationContext(),exampleActivity.class);

///////////////////////////////////////////////////////////////////////////////////////////////////

//여기서 exampleActivity로 이동해서 똑같이 mTankConService.write()에 값을 보내도록하려면...질문핵심

///////////////////////////////////////////////////////////////////////////////////////////////////
startActivity(intent);
//mTankConService.write(0x01);
}
else if (v.getId() == R.id.btnB)
mTankConService.write(0x02);
else if (v.getId() == R.id.btnL)
mTankConService.write(0x03);
else if (v.getId() == R.id.btnR)
mTankConService.write(0x04);
else {
mTankConService.write(0x05);
}
}
}

//////////////////////////////////////////////////////////////////////////////////////////////

//핸들러부분은 아직 공부덜해서 모르겠네요 ㅠ.ㅠ 왠지 이 밑에 핸들러부분때문에 문제가 있는게 아닌지...??

/////////////////////////////////////////////////////////////////////////////////////////////
// The Handler that gets information back from the BluetoothChatService

private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (D)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case TankConService.STATE_CONNECTED:
mStatus.setText(R.string.status_connected_to);
mStatus.append(mConnectedDeviceName);
break;
case TankConService.STATE_CONNECTING:
mStatus.setText(R.string.status_connecting);
break;
case TankConService.STATE_LISTEN:
case TankConService.STATE_NONE:
mStatus.setText(R.string.status_not_connected);
break;
}
break;
// TODO: remove MESSAGE_READ
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
// mConversationArrayAdapter.add(mConnectedDeviceName+": " +
// readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"Connected to " + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
.show();
break;
}
}
};
}

여기까지가 소스였구요 부분부분 주석을 달아가면서 이해하려고 노력중이었는데요 ``

소스에서 질문 핵심이라구 해놓은게 주 질문입니다

example엑티비티로 이동해서 TankConService 클래스안의 write()메소드를 실행하려면 어떠케 해야할지...

수십번 이러케 저렇게 해봤는데 ㅠ.ㅠ 안되서 마지막방법으로 질문을 올려서 조언을 얻어보려합니다..

지금까지 생각으로는 TankConService클래스를 위 자바파일처럼 example.java에서도 TankConService 를 mTankConService = null;

이러케 참조해서 mTankConService.wirte() 이런식으로 테스트 하려했는데 아마도.. mTankConService 안에 상태값??

그런게 참조안되서 응용프로그램이 예상치않게 종료되었다 그러는거 같아요 ``;;

그래서 여기안에있는 내용을 똑같이 컨트롤C, V 하여 버튼만 다르게 해서 참조하는 레이아웃을 바꿔주고

그 레이아웃에 있는 새로운 버튼들을 엑티비티에 참조해서 똑같은방법으로 mTankConService안의 wirte메소드에

값을 보내는방법도 해봤지만 `` 스코프를 찍어본결과... A엑티비티 즉 위의소스 엑티비티는 128포트에서 값을받는데..

A엑티비티의 버튼중 하나의버튼으로 B엑티비티로 이동해서 똑같은 소스에 xml과 버튼들이 다른 버튼 몇개있는 B엑티비티에서

mTankConService안의 메소드 write메소드를 불러서 값을 전달하는데까지 소스상 오류는없었지만.. 이방법은 야매로 상각했지만..

역시나 스코프를 찍어본결과 값이 날라오지않았네요... 질문의 답변은.. B엑티비티에 필요한것들...어떠케하면 mTankConService에 wirte메소드를 쓸수있는지 `` 그런 답변 기대하고있겠습니다 ㅠ.ㅠ 혹시 몰라 mTankConService의 클래스 TankConService의 소스도 첨부하겠습니다^^;;

 

-------------------TankConService.java---------------------

package com.example.sendbluetooth;

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

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


public class TankConService {
    // Debugging
    private static final String TAG = "TankConService";
    private static final boolean D = true;

    // Name for the SDP record when creating server socket
    private static final String NAME = "TankCon";

    // Generic UUID for SPP
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
   
    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device


    public TankConService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

  
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "start");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to listen on a BluetoothServerSocket
        if (mAcceptThread == null) {
            mAcceptThread = new AcceptThread();
            mAcceptThread.start();
        }
        setState(STATE_LISTEN);
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(TAG, "connect to: " + device);

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(TAG, "connected");

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
        setState(STATE_NONE);
    }
//////////////////////////////////////////////////////////////////////////////////////////
    public void write(int zip){
     ConnectedThread r;
      synchronized (this) {
             if (mState != STATE_CONNECTED) return;
             r = mConnectedThread;
         }
         // Perform the write unsynchronized
         r.write(zip);
    }

/////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
     if (D) Log.d(TAG, "connectionFailed");
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
     if (D) Log.d(TAG, "connectionLost");
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;

            // Create a new listening server socket
            try {
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "listen() failed", e);
            }
            mmServerSocket = tmp;
        }

        @Override
  public void run() {
            if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
            setName("AcceptThread");
            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "accept() failed", e);
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (TankConService.this) {
                        switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice());
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected. Terminate new socket.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D) Log.i(TAG, "END mAcceptThread");
        }

        public void cancel() {
            if (D) Log.d(TAG, "cancel " + this);
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of server failed", e);
            }
        }
    }


    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
            }
            mmSocket = tmp;
        }

        @Override
  public void run() {
            Log.i(TAG, "BEGIN mConnectThread");
            setName("ConnectThread");

            // Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
            } catch (IOException e) {
                connectionFailed();
                // Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() socket during connection failure", e2);
                }
                // Start the service over to restart listening mode
                TankConService.this.start();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (TankConService.this) {
                mConnectThread = null;
            }

            // Start the connected thread
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        @Override
  public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                 // TODO: add dogkick!!
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

/////////////////////////////////////////////////////////////////////////
        public void write(int zip){
         try{
          mmOutStream.write(zip);
         }catch(IOException e){}
        }

//////////////////////////////////////////////////////////////////////////
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }
}

 

 방법or조언 좀 부탁드립니다....

매니페스트에 엑티비티 선언같은건 다 해줬구요.. 블루투스 관련 퍼미션두 다 했습니다 ㅠ.ㅠ

도와주세요 ~~~ㅠ.ㅠ