ConnectionRegister.java 2.0 KB

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