【问题标题】:Greenrobot EventBus3 not posting to my subscribersGreenrobot EventBus3 未发布给我的订阅者
【发布时间】:2016-05-16 08:49:19
【问题描述】:

在我的申请中,我将job 传递给job-queue,在我的工作队列中,我已经注册了我的EventBus,我正在尝试post 事件,希望我的subscriber方法会收到它。我刚刚从 Otto's EventBus 迁移,虽然这种方式以前有效,但它不适用于 greenrobots EventBus 3。

这是我想要实现的示例案例:

TestPresenterImpl.class(这个类已经实例化了TestActivity.class

@Override
public void addJob(JobData jobData) {
    jobManager.addJobInBackground(new SendUpdateJob(jobData));
}

@Subscribe
@Override
public void onUpdate(JobAddedEvent event) {
    if (event.getStatus() == 1) {
        Log.i(LOG_TAG, "test");
    }
}

@Override
public void onStart() {
    mBus.getDefault().register(this);
}

@Override
public void onStop() {
    mBus.getDefault().unregister(this);
}

SendUpdateJob.class(这个类使用之前由 Path 维护的 android-priority-job 队列来处理队列中的作业)

@Override
public void onAdded() {
    Log.i(LOG_TAG, "On added");
    mBus.getDefault().register(this);
    JobAddedEvent event = new JobAddedEvent();
    event.setStatus(1);

    mBus.getDefault().post(event);
}

通常这适用于Otto,但由于这略有不同,我想知道我做错了什么。我得到的错误是:..."SendJobUpdate and its super classes have no public methods with the @Subscribe annotation".我在这里做错了吗?

我还确保我正在导入 import org.greenrobot.eventbus.Subscribe; ,因为我注意到其他人指出他们已经导入了谷歌 subscribe

【问题讨论】:

    标签: java android queue


    【解决方案1】:

    您的EventBus.getDefault().register(this); 应该跟随您的@Subscribe 方法所在的活动,而不是mBus.getDefault().post(event); 活动。

    第一活动

    public class FirstActicity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        //register should in this activity
        EventBus.getDefault().register(this);
    }
    
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(MessageEvent event) {
        //eventbus notify
        Log.i("2hh", "main --- eventbus ---- updatedata");
        queryData();
    }
    
    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
    

    SecondActivity(不要注册这个活动,因为你没有任何@Subscribe方法)

    public class SecondActivity extends AppCompatActivity implements{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
    
        EventBus.getDefault().post(new MessageEvent("updateData"));
    
    
    }
    

    }

    【讨论】:

    • 我提交了一个编辑以更好地格式化您的答案并专注于有用的部分。请您将代码复制并粘贴到您的图像中而不是使用图像吗?它更易于阅读、搜索并防止链接失效。
    • 好的,对此我很抱歉,我是新手没想到,我会尽快更改答案,谢谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多