Reputation: 91
I want to work on my data depending on what Lifecycle state I have.
For example, I want to do something, when the application was resumed. How can I find out in what State is my app now? Thanks for help.
Upvotes: 9
Views: 14293
Reputation: 904
in activity: if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) ...
I think. If you're asking about async tasks.
Upvotes: 18
Reputation: 1278
There are predefined methods of an Activity. Please review Life cycle of an Activity in Android.
Example code
public class LifeCycleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(LifeCycleActivity.this,"ON CREATE", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(LifeCycleActivity.this,"ON START", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(LifeCycleActivity.this,"ON RESUME", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(LifeCycleActivity.this,"ON PAUSE", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText(LifeCycleActivity.this,"ON RESTART", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(LifeCycleActivity.this,"ON STOP", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(LifeCycleActivity.this,"ON DESTROY", Toast.LENGTH_SHORT).show();
}
}
Also read: - https://developer.android.com/guide/components/activities/activity-lifecycle.html
Upvotes: 0
Reputation: 4737
For custom class you can use lifecycle from architecture components, first add library
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
then your custom class, for example
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener() {
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener() {
...
}
}
and finally from your lifecycle container (activity/fragment)
myActivity.getLifecycle().addObserver(new MyObserver());
More info here https://developer.android.com/topic/libraries/architecture/lifecycle.html
Upvotes: 0