안녕하세요, 블루투스 활용한 앱을 개발하고 있습니다.
책도 찾아보고 무엇이 문제인지 며칠째 해결책을 찾아보고, 성공앱들에서
되는 부분 복붙도 해보았는데 도무지 해결방안을 찾지 못해 질문드립니다.
많은 도움 부탁드립니다!
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 업데이트
*/