2013-06-13 6 views
1

좋아, 나는 안드로이드에 익숙하지 않다, 나는 블루투스를 통해 arduino와 인터페이스하는 응용 프로그램을 만들려고 노력하고있다. 나는 샘플 BluetoothChat을보고 "서비스", 그것으로 생성 된 스레드와 MainActivity 사이에서 통신하기 위해 Handler를 사용하는 방법을 보았습니다. 문제는 블루투스 서비스를 사용해야하는 활동이 두 개 이상 있다는 것입니다. 각 활동에 대한 나는이 같은 핸들러가 있습니다처리기 및 다중 활동

private BtService(){ 
    btm = BluetoothAdapter.getDefaultAdapter(); 
    mHandler= new Handler(Looper.getMainLooper()); 
} 

내가 메시지를 보낼 필요로 할 때 나는 이렇게 :

 mHandler = new Handler(){ 
     @Override 
     public void handleMessage(Message message) { 
      switch (message.what){ 
      case BtService.CHANGE_STATE: 
       if (message.arg1 == BtService.STATE_CONNECTING){ 
        Intent i = new Intent (MainActivity.this,ConnectedActivity.class); 
        startActivity(i); 

       } 
       break; 
      } 
     } 

    }; 

와 서비스 생성자에서 나는이있어

private synchronized void setState(int state){ 
    mHandler.obtainMessage(CHANGE_STATE, state, -1).sendToTarget(); 
    mState = state; 
} 

그러나 메시지는 여러 다른 Handlers에서 수신되지 않습니다. here에 "특정 스레드에 대한 모든 처리기 개체가 동일한 메시지를받습니다." 그래서 나는 그 문제를 이해할 수 없다. 활동이 시작될 때마다 해당 활동에서 메시지를 수신하도록 처리기가 선언 한 서비스에 전달해야합니까? 이것은 효과가있는 것 같지만, 나에게는 좋은 습관이 아닙니다.

답변

0

각 활동이 블루투스를 통해 연결하는 대신 응용 프로그램 계층을 확장하고이를 사용하여 스레드를 유지 관리하여 블루투스 연결을 통해 수집 된 데이터를 검색하고 관리 할 수 ​​있습니다. 그런 다음 각 액티비티에서 핸들러를 사용하여 필요할 경우 애플리케이션 계층에서 수집 한 데이터에 대해 새로 고침합니다.

나의 btAdapter 및 소켓과의 활동은 메뉴 및 bt 구성 활동 후 실제로 블루투스 정보가 필요한 첫 번째 활동입니다. 내 첫 번째 활동 onRusume()에서

는 의견이 설명이 같이 보입니다 .. : 꽤 많이 나는 나를 위해 일을하는 데있어 방법의 핵심입니다

@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 = 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..."); 
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..."); 

/** 
* **Here I am kicking off the thread in the application that retrieves all data 
* needed by all my activities. Then it stores the information in its member 
* variables. Each activity then refreshes as often as needed, gets the data from 
* the application layer it needs and does some logic on it.** 
*/ 
if(mConnectedThread == null) { 
    mConnectedThread = app.new ConnectedThread(btSocket); 
    mConnectedThread.start(); 
} 

// This kicks off the handler for this activity that refreshes the activity every 
// xxxx ms and checks the data retrieved from bt in the application layer. 
startUpdatingTicketView(); 
} 

합니다.

추가 참고 사항 ... 백그라운드 서비스에서 관리되는 bt 통신으로이 작업을 시도했지만 올바르게 작동하지 못했습니다. 내가 겪고 있던 문제가 정확히 무엇인지를 잊었고 서비스를 사용하는 것이 효과적 일 수는 있지만이 경로를 끝내지는 못했습니다.

행운을 빈다.

+0

은 미안하게하지 않은 경우,이

환호 helpfull이다

BroadcastReceiver connectionUpdates = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { ...//TODO here } }; LocalBroadcastManager.getInstance(this).registerReceiver( connectionUpdates , new IntentFilter(ApplicationConstants.MY_MESSAGE)); 

희망을 (당신은 두 개 이상의 활동에 이것을 사용 모시) "진정한"질문은 "스레드의 모든 처리기가 API 교육에 언급 된 것과 동일한 메시지를 받거나 잘못 이해하고있는 것이 사실인가"입니다. 어쨌든, 답변 해 주셔서 감사합니다. – Campig

3

모든 응용 프로그램에서 메시지를 보내려면 BroadcastReceiver를 사용해야합니다.이 경우가 최선의 방법입니다.

Intent intent = new Intent(ApplicationConstants.MY_MESSAGE); 
LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 

모든 활동에 메시지를 수신