如何使用Android Annotation将Activity实例注入到我的BroadcastReceiver中?

时间:2017-02-06 15:10:39

标签: dependency-injection android-annotations

我曾经在活动中使用简单的广播听众,在那里做一些像textView.setText(" text")这样的事情;但听众变得非常大,留在里面,我把它分开了。 我喜欢AA,我只想继续管理来自我已分离的BroadcastReceiver的当前活动的视图。但是,当我做类似的事情时:

@EReceiver
public class WarningActivityStateListener extends BroadcastReceiver {
    @RootContext //or Bean
    WarningActivity activity;

我有一个错误:

Error:(25, 2) error: org.androidannotations.annotations.RootContext can only be used in a class annotated with @org.androidannotations.annotations.EBean.

如果我尝试在上面添加@EBean,那我就更糟了:

Error:(27, 28) error: Something went wrong: Unexpected error in AndroidAnnotations 4.2.0!
You should check if there is already an issue about it on https://github.com/androidannotations/androidannotations/search?q=java.lang.ClassCastException&type=Issues
If none exists, please open a new one with the following content and tell us if you can reproduce it or not. Don't forget to give us as much information as you can (like parts of your code in failure).

1 个答案:

答案 0 :(得分:0)

你不能这样做,因为Context的{​​{1}}是接收者本身,它与任何BroadcastReceiver无关。您只能在此处使用Activity注释注入应用Context

修改

您可以使用@AppActivity中注释一个方法,该方法将处理接收@ReceiverIntent注册/注销:

BroadcastReceiver

或者您可以创建普通@EActivity public class MyActivity extends Activity { @Receiver(actions = "org.androidannotations.ACTION_1") protected void onAction1() { // Will be called when an org.androidannotations.ACTION_1 intent is sent. } } ,并通过事件总线或BroadcastReceiver将事件从onReceive方法发送到Activity