2

I am using android annotations and have some code that I need to execute in the onResume() function in my activity.

Is it safe to just override the onResume function from the android annotation activity (ie with @EActivity)?

MattCochrane
  • 2,900
  • 2
  • 25
  • 35

3 Answers3

5

Yeah, you should use these lifecycle methods just like with plain Android activities. There is one thing though: injected Views are not yet available in your onCreate method, this is why @AfterViews exist:

@EActivity(R.layout.views_injected)
public class ViewsInjectedActivity extends Activity {

    @ViewById
    Button myButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // myButton is not yet available here
    }

    @AfterViews
    void setupViews() {
        // myButton is first available here
        myButton.setText("Hello");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // just as usual
    }
}
WonderCsabo
  • 11,947
  • 13
  • 63
  • 105
  • 2
    is it safe to assume that all injected views are available in the ```onResume``` method? – swalkner Nov 20 '15 at 19:21
  • 3
    @swalkner yes. See [here](http://stackoverflow.com/a/33833912/747412) when `@AfterViews` is called. – WonderCsabo Nov 20 '15 at 20:20
  • 1
    I wasnt sure about this, but I had a clue with the documentation here: ```@AfterViews will be called everytime setContentView() is called. (Activity only)```. Then if @Afterviews is called after the content is set, it means onCreate was finished and then the next step in the lifecycle is onResume https://github.com/excilys/androidannotations/wiki/%40AfterXXX-call-order – cutiko May 16 '16 at 13:34
2

Yeah. Just call super.onResume() and then add your code.

I'd do it just like their on create example here: https://github.com/excilys/androidannotations/wiki/Enhance-activities

Elltz
  • 10,730
  • 4
  • 31
  • 59
Jacob Holloway
  • 887
  • 8
  • 24
0

You can bind your custom class with lifecycle component of android. It holds life cycle information of android component so that your custom class observe lifecycle changes.

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());
Brijesh Gupta
  • 487
  • 4
  • 8