2016-09-21 2 views
0

내 프로그램에는 새로운 Bluetooth ConnectedThread를 만들고있는 BroadcastReceiver이 있습니다.기존 스레드에 대한 액세스 얻기

그러나이 스레드는 다른 범위 (수신기 외부의 메서드)에 액세스해야합니다. thread.write(bytesWrite); 다른 스레드를 만들고 싶지 않습니다. 기존 스레드에 액세스해야합니다. 또한 알 수없는 매개 변수 (btSocket)를 넣을 수 없으므로 수신기 외부에서 스레드를 선언 할 수 없습니다.

이 문제를 해결하는 방법은 무엇입니까?

답변

0

방금 ​​만든 스레드에 대한 참조를 static 참조로 유지하는 것입니다. 당신의 접수에서 수행

그런 다음 당신이있어 어떤 클래스
public YourReceiver extends BroadcastReceiver { 
    @Nullable public static ConnectedThread thread; 

    public void onReceive(...) { 
    thread = new ConnectedThread(btSocket); 
    thread.start(); 
    } 
} 

, 당신은 YourReceiver.thread를 통해 스레드를 참조 할 수 있습니다.

이 접근법의 가장 큰 단점은 ConnectionThread에 정적 참조를 유지하는 것이 낭비입니다 (해당 참조를 해제해야만 ConnectionThread이 GC되지 않음). 완료되면 언제든지 무효화해야합니다. 또 다른 문제는 스레드를 사용하기 전에 스레드의 내부 상태, 즉 스레드가 실행 중인지 또는 이미 실행이 완료되었는지 여부를 확인해야합니다.

  1. ConnectThread
  2. ConnectThread의 참조를 얻기 위해 ConnectThread
  3. 다른 범위

에서 스레드를 생성하는 하나

0

당신은 적어도 3 개 개의 스레드를 가지고 , 스레드 2 (ConnectThread를 생성하는 스레드)와 스레드 3 (다른 범위의 스레드)에서 사용할 수있는 것이 필요합니다.

ConnectedThread thread = new ConnectedThread(btSocket); 
ThreadHolder.connectedThread=thread; 
thread.start(); 

에서 : 스레드 2에서

public class ThreadHolder{ 
    public static ConnectedThread connectedThread 
} 

당신이 참조를 설정 :

간단한 방법은 스레드의 참조를 보유하고 정적 변수와 클래스 ThreadHolder을 가지고, 수 스레드 3을 찾으셨습니까?

또는 ConnectedThread에 다음을 제공 할 수 있습니다. 스레드 2 이름 :

thread.setName ("connectedThread")

그리고이 방법을 사용하여 htread 3에서 찾을 :

public Thread getThreadByName(String threadName) { 
    for (Thread t : Thread.getAllStackTraces().keySet()) { 
    if (t.getName().equals(threadName)) return t; 
    } 
    return null; 
} 

find thread by name

참조
관련 문제