2014-12-23 3 views
1

나는 Otto을 사용하려고합니다. 지금까지는 효과가 있다고 생각하지만 이벤트를 두 번받습니다. 두 번받은 오토 이벤트

내가 (내가 다음에 example on GitHub) 한 것입니다 :

프로듀서 :

public class NetworkChangeReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(final Context context, final Intent intent) 
    { 
     Log.i("ralphs", "onReceive"); 

     // .... more stuff 

     final Bus bus = TRaumfeldApp.getInstance().getBus(); 
     bus.register(this); 
     bus.post(new NetworkChangeEvent()); 
     bus.unregister(this); 
    } 

    @Produce 
    public NetworkChangeEvent produceAnswer() 
    { 
     Log.i("ralphs", "produceAnswer"); 
     return new NetworkChangeEvent(); 
    } 
} 

가입자 :이 같은

public class MainActivity extends ActionBarActivity 
{ 
    private Bus    mBus; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // otto event bus 
     mBus = TRaumfeldApp.getInstance().getBus(); 
    } 

    @Override 
    protected void onResume() 
    { 
     super.onResume(); 
     mBus.register(this); 
    } 

    @Override 
    protected void onPause() 
    { 
     super.onPause(); 
     mBus.unregister(this); 
    } 

    @Subscribe 
    public void answerAvailable(NetworkChangeEvent event) 
    { 
     Log.i("ralphs", "answerAvailable"); 
    } 
} 

로그 잠금 :

I/ralphs﹕ onReceive 
I/ralphs﹕ produceAnswer 
I/ralphs﹕ answerAvailable 
I/ralphs﹕ answerAvailable 

왜 이벤트가 두 번 수신됩니까?

답변

3

구독자가 등록하면 이러한 메서드가있는 개체가 등록되어있는 경우 첫 번째 이벤트가 @Produce- 주석 처리 된 메서드에서 가져옵니다. 두 번째 이벤트는 명시적인 post() 작업의 이벤트입니다.

게시하려면 등록 할 필요가 없지만 @Produce 주석은 필요합니다.

1

이벤트를 게시하려면 등록 할 필요가 없습니다.

0

내가 아는 한,이 문제는 올바르게 작동하는 Otto Events Bus와 관련이 없습니다. 이 버그는 Android API 및 네트워크 변경 이벤트의 브로드 캐스트 수신기와 관련이 있습니다. 그것은 또한 장치 특정 문제입니다. 일부 장치는 2 또는 3 개의 네트워크 변경 이벤트를 수신 할 수 있습니다. 예 :라는 클래스를 만들어 문제를 처리 할 수 ​​있습니다. 연결 상태가 변경된 경우에만 네트워크 연결의 현재 상태를 나타내는 정적 변수가있는 NetworkState 및 이벤트를 버스에 게시합니다. 이 문제는 NetworkEvents 라이브러리에서 처리되었습니다. 소스 코드를 찾아보고 거기에서 처리 된 방법을 보거나 프로젝트에서이 라이브러리를 사용할 수 있습니다. 특히 NetworkConnectionChangeReceiver 클래스를 살펴볼 수 있습니다. 최상의 솔루션은 아니지만 브로드 캐스트 수신기가 예상대로 작동하지 않을 때까지는 아무 것도 할 수 없습니다.