Skip to content

Instantly share code, notes, and snippets.

@mayuroks
Created July 10, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayuroks/12fa26b6dd0b5c27ef6d9ba8689ec95d to your computer and use it in GitHub Desktop.
Save mayuroks/12fa26b6dd0b5c27ef6d9ba8689ec95d to your computer and use it in GitHub Desktop.
/**
* Closes the socket connection when app is in background and
* connects to socket when the app is in foreground.
*/
public class AppLifeCycleObserver implements LifecycleObserver {
private Context mContext;
/**
* Use this constructor to create a new AppLifeCycleObserver
*
* @param context
*/
public AppLifeCycleObserver(Context context) {
mContext = context;
}
/**
* When app enters foreground
*/
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnterForeground() {
try {
EventServiceImpl.getInstance().connect(User.getUsername());
} catch (URISyntaxException e) {
Toast.makeText(mContext, "Failed to connect to chat server.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
/**
* When app enters background
*/
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnterBackground() {
EventServiceImpl.getInstance().disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment