NGMediaReceiveCallbackAndroid.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #if UNITY_EDITOR || UNITY_ANDROID
  2. using UnityEngine;
  3. namespace NativeGalleryNamespace
  4. {
  5. public class NGMediaReceiveCallbackAndroid : AndroidJavaProxy
  6. {
  7. private readonly NativeGallery.MediaPickCallback callback;
  8. private readonly NativeGallery.MediaPickMultipleCallback callbackMultiple;
  9. private readonly NGCallbackHelper callbackHelper;
  10. public NGMediaReceiveCallbackAndroid( NativeGallery.MediaPickCallback callback, NativeGallery.MediaPickMultipleCallback callbackMultiple ) : base( "com.yasirkula.unity.NativeGalleryMediaReceiver" )
  11. {
  12. this.callback = callback;
  13. this.callbackMultiple = callbackMultiple;
  14. callbackHelper = new GameObject( "NGCallbackHelper" ).AddComponent<NGCallbackHelper>();
  15. }
  16. public void OnMediaReceived( string path )
  17. {
  18. callbackHelper.CallOnMainThread( () => MediaReceiveCallback( path ) );
  19. }
  20. public void OnMultipleMediaReceived( string paths )
  21. {
  22. string[] result = null;
  23. if( !string.IsNullOrEmpty( paths ) )
  24. {
  25. string[] pathsSplit = paths.Split( '>' );
  26. int validPathCount = 0;
  27. for( int i = 0; i < pathsSplit.Length; i++ )
  28. {
  29. if( !string.IsNullOrEmpty( pathsSplit[i] ) )
  30. validPathCount++;
  31. }
  32. if( validPathCount == 0 )
  33. pathsSplit = new string[0];
  34. else if( validPathCount != pathsSplit.Length )
  35. {
  36. string[] validPaths = new string[validPathCount];
  37. for( int i = 0, j = 0; i < pathsSplit.Length; i++ )
  38. {
  39. if( !string.IsNullOrEmpty( pathsSplit[i] ) )
  40. validPaths[j++] = pathsSplit[i];
  41. }
  42. pathsSplit = validPaths;
  43. }
  44. result = pathsSplit;
  45. }
  46. callbackHelper.CallOnMainThread( () => MediaReceiveMultipleCallback( result ) );
  47. }
  48. private void MediaReceiveCallback( string path )
  49. {
  50. if( string.IsNullOrEmpty( path ) )
  51. path = null;
  52. try
  53. {
  54. if( callback != null )
  55. callback( path );
  56. }
  57. finally
  58. {
  59. Object.Destroy( callbackHelper.gameObject );
  60. }
  61. }
  62. private void MediaReceiveMultipleCallback( string[] paths )
  63. {
  64. if( paths != null && paths.Length == 0 )
  65. paths = null;
  66. try
  67. {
  68. if( callbackMultiple != null )
  69. callbackMultiple( paths );
  70. }
  71. finally
  72. {
  73. Object.Destroy( callbackHelper.gameObject );
  74. }
  75. }
  76. }
  77. }
  78. #endif