ConnectionRegister.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package de.tudarmstadt.informatik.hostage;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import android.preference.PreferenceManager;
  5. /**
  6. * Saves the amount of active connections and limits them to a specific number.
  7. * @author Wulf Pfeiffer
  8. */
  9. public class ConnectionRegister {
  10. /** Active connections . **/
  11. private static int openConnections = 0;
  12. /** Context in which ConnectionRegister is created. **/
  13. private Context context;
  14. /**
  15. * Constructor sets context.
  16. * @param context Context in which ConnectionRegister is created.
  17. */
  18. public ConnectionRegister(Context context){
  19. this.context = context;
  20. }
  21. /**
  22. * Returns the maximum number of active connections.
  23. * @return maximum number of active connections.
  24. */
  25. public int getMaxConnections() {
  26. SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(context);
  27. return defaultPref.getInt("max_connections", 5);
  28. }
  29. /**
  30. * Returns the number of active connections.
  31. * @return number of active connections.
  32. */
  33. public int getOpenConnections() {
  34. return openConnections;
  35. }
  36. /**
  37. * Returns if there are new connections allowed or not.
  38. * @return true if a new connection is allowed, else false.
  39. */
  40. public boolean isConnectionFree() {
  41. return getMaxConnections() == 0 || openConnections < getMaxConnections();
  42. }
  43. /**
  44. * Registers a new active connection if there are connections allowed.
  45. * @return true if a new connection has been successfully registered, else false.
  46. */
  47. public boolean newOpenConnection() {
  48. if(isConnectionFree()) {
  49. openConnections++;
  50. return true;
  51. } else {
  52. return false;
  53. }
  54. }
  55. /**
  56. * Deregisters a active connection if at least one active connection is registered.
  57. * @return true if the connection has been successfully unregistered, else false.
  58. */
  59. public boolean closeConnection() {
  60. if(openConnections > 0) {
  61. openConnections--;
  62. return true;
  63. } else {
  64. return false;
  65. }
  66. }
  67. }