Otto 이벤트 버스를 사용하여 서비스에서 활동으로 이벤트를 보내는 방법은 무엇입니까?
단순한 BusProvider.getInstance().post()예외가 아닙니다 main thread. Otto 이벤트 버스를 사용하여 서비스에서 활동으로 이벤트를 보내는 방법은 무엇입니까?
모든 스레드 (메인 또는 백그라운드)에서 게시하고 메인 스레드에서 수신하려면 다음과 같이 시도하십시오.
public class MainThreadBus extends Bus {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
MainThreadBus.super.post(event);
}
});
}
}
}
참고 : 일반적인 접근 방식에 대해서는 https://github.com/square/otto/issues/38의 Jake Wharton과 "pommedeterresaute"가 크레딧을받습니다 . 서브 클래스가 아닌 래퍼 클래스로 구현했습니다.
모든 스레드 (메인 또는 백그라운드)에서 게시하고 메인 스레드에서 수신하려면 MainThreadBus바닐라 대신 다음을 사용하십시오.Bus
public class MainThreadBus extends Bus {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
handler.post(new Runnable() {
@Override
public void run() {
MainThreadBus.super.post(event);
}
});
}
}
}
이것은 Andy Dennie의 답변을 기반으로합니다.
Bus개체를 확장하고 감싸거나 둘 중 하나를 수행 할 필요가 없습니다 . 사실상 래퍼 인 Dennie의 대답에서 Bus기본 클래스는 인터페이스처럼 사용되며 모든 기능을 덮어 씁니다.
Bus참조 MainThreadBus를 통해 참조하지 않는 한 기본 클래스 를 제거하더라도 작동 Bus합니다.
또는 메인이 아닌 스레드에서 게시하는 것이 확실한 경우 다음과 같이하십시오.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mBus.post(new myEvent());
}
});
"단순하고 어리석게 유지"라는 속담처럼 :)
버스 = new Bus (ThreadEnforcer.ANY); 이 문제에 대한 명확한 해결책입니다. 당신이해야 할 모든 것.
나를위한 최고의 구현 맞춤형 버스 클래스
public class AndroidBus extends Bus {
private final Handler mainThread = new Handler(Looper.getMainLooper());
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
mainThread.post(() -> AndroidBus.super.post(event));
}
}
}
나는 간단하게했다 :
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
bus.post(event);
}
});
행복한 코딩 .. :)
Just create the BasicBus with ThreadEnforcer.NONE to post event from non-main threads. The mentioned ThreadEnforcer.MAIN is exactly the opposite (and the default), which accepts only posts from the main-thread.
'Program Tip' 카테고리의 다른 글
| Pandas to_csv가있는 float64 (0) | 2020.12.11 |
|---|---|
| angularjs를 사용한 두 개의 중첩 클릭 이벤트 (0) | 2020.12.10 |
| 사용자 이름과 암호를 제공하지 않고 공유 폴더에 액세스하는 방법 (0) | 2020.12.10 |
| 여러 표현식에서 ng-click을 사용하는 방법은 무엇입니까? (0) | 2020.12.10 |
| Intent.VIEW_ACTION이있는 Android 설치 APK가 파일 공급자와 작동하지 않음 (0) | 2020.12.10 |