ConnectionRegister.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. *
  8. * @author Wulf Pfeiffer
  9. * @author Lars Pandikow
  10. */
  11. public class ConnectionRegister {
  12. /** Active connections . **/
  13. private static int openConnections = 0;
  14. /** Context in which ConnectionRegister is created. **/
  15. private Context context;
  16. /**
  17. * Constructor sets context.
  18. *
  19. * @param context
  20. * Context in which ConnectionRegister is created.
  21. */
  22. public ConnectionRegister(Context context) {
  23. this.context = context;
  24. }
  25. /**
  26. * Deregisters a active connection if at least one active connection is
  27. * registered.
  28. *
  29. * @return true if the connection has been successfully unregistered, else
  30. * false.
  31. */
  32. public boolean closeConnection() {
  33. if (openConnections > 0) {
  34. openConnections--;
  35. return true;
  36. } else {
  37. return false;
  38. }
  39. }
  40. /**
  41. * Returns the maximum number of active connections.
  42. *
  43. * @return maximum number of active connections.
  44. */
  45. public int getMaxConnections() {
  46. SharedPreferences defaultPref = PreferenceManager
  47. .getDefaultSharedPreferences(context);
  48. return Integer.parseInt(defaultPref.getString("pref_max_connections", "5"));
  49. }
  50. /**
  51. * Returns the number of active connections.
  52. *
  53. * @return number of active connections.
  54. */
  55. public int getOpenConnections() {
  56. return openConnections;
  57. }
  58. /**
  59. * Returns if there are new connections allowed or not.
  60. *
  61. * @return true if a new connection is allowed, else false.
  62. */
  63. public boolean isConnectionFree() {
  64. return getMaxConnections() == 0
  65. || openConnections < getMaxConnections();
  66. }
  67. /**
  68. * Registers a new active connection if there are connections allowed.
  69. *
  70. * @return true if a new connection has been successfully registered, else
  71. * false.
  72. */
  73. public boolean newOpenConnection() {
  74. if (isConnectionFree()) {
  75. openConnections++;
  76. return true;
  77. } else {
  78. return false;
  79. }
  80. }
  81. }