CallbackMap.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. package org.apache.cordova;
  18. import android.util.Pair;
  19. import android.util.SparseArray;
  20. /**
  21. * Provides a collection that maps unique request codes to CordovaPlugins and Integers.
  22. * Used to ensure that when plugins make requests for runtime permissions, those requests do not
  23. * collide with requests from other plugins that use the same request code value.
  24. */
  25. public class CallbackMap {
  26. private int currentCallbackId = 0;
  27. private SparseArray<Pair<CordovaPlugin, Integer>> callbacks;
  28. public CallbackMap() {
  29. this.callbacks = new SparseArray<Pair<CordovaPlugin, Integer>>();
  30. }
  31. /**
  32. * Stores a CordovaPlugin and request code and returns a new unique request code to use
  33. * in a permission request.
  34. *
  35. * @param receiver The plugin that is making the request
  36. * @param requestCode The original request code used by the plugin
  37. * @return A unique request code that can be used to retrieve this callback
  38. * with getAndRemoveCallback()
  39. */
  40. public synchronized int registerCallback(CordovaPlugin receiver, int requestCode) {
  41. int mappedId = this.currentCallbackId++;
  42. callbacks.put(mappedId, new Pair<CordovaPlugin, Integer>(receiver, requestCode));
  43. return mappedId;
  44. }
  45. /**
  46. * Retrieves and removes a callback stored in the map using the mapped request code
  47. * obtained from registerCallback()
  48. *
  49. * @param mappedId The request code obtained from registerCallback()
  50. * @return The CordovaPlugin and orignal request code that correspond to the
  51. * given mappedCode
  52. */
  53. public synchronized Pair<CordovaPlugin, Integer> getAndRemoveCallback(int mappedId) {
  54. Pair<CordovaPlugin, Integer> callback = callbacks.get(mappedId);
  55. callbacks.remove(mappedId);
  56. return callback;
  57. }
  58. }