android_gallery.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from kivy.logger import Logger
  2. from kivy.clock import Clock
  3. from jnius import autoclass
  4. from jnius import cast
  5. from android import activity
  6. PythonActivity = autoclass('org.kivy.android.PythonActivity')
  7. Intent = autoclass('android.content.Intent')
  8. Uri = autoclass('android.net.Uri')
  9. MEDIA_DATA = "_data"
  10. RESULT_LOAD_IMAGE = 1
  11. Activity = autoclass('android.app.Activity')
  12. def user_select_image(on_selection):
  13. """Open Gallery Activity and call callback with absolute image filepath of image user selected.
  14. None if user canceled.
  15. """
  16. currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
  17. # Forum discussion: https://groups.google.com/forum/#!msg/kivy-users/bjsG2j9bptI/-Oe_aGo0newJ
  18. def on_activity_result(request_code, result_code, intent):
  19. if request_code != RESULT_LOAD_IMAGE:
  20. Logger.warning('user_select_image: ignoring activity result that was not RESULT_LOAD_IMAGE')
  21. return
  22. if result_code == Activity.RESULT_CANCELED:
  23. Clock.schedule_once(lambda dt: on_selection(None), 0)
  24. return
  25. if result_code != Activity.RESULT_OK:
  26. # This may just go into the void...
  27. raise NotImplementedError('Unknown result_code "{}"'.format(result_code))
  28. selectedImage = intent.getData(); # Uri
  29. filePathColumn = [MEDIA_DATA]; # String[]
  30. # Cursor
  31. cursor = currentActivity.getContentResolver().query(selectedImage,
  32. filePathColumn, None, None, None);
  33. cursor.moveToFirst();
  34. # int
  35. columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  36. # String
  37. picturePath = cursor.getString(columnIndex);
  38. cursor.close();
  39. Logger.info('android_ui: user_select_image() selected %s', picturePath)
  40. # This is possibly in a different thread?
  41. Clock.schedule_once(lambda dt: on_selection(picturePath), 0)
  42. # See: http://pyjnius.readthedocs.org/en/latest/android.html
  43. activity.bind(on_activity_result=on_activity_result)
  44. intent = Intent()
  45. # http://programmerguru.com/android-tutorial/how-to-pick-image-from-gallery/
  46. # http://stackoverflow.com/questions/18416122/open-gallery-app-in-android
  47. intent.setAction(Intent.ACTION_PICK)
  48. # TODO internal vs external?
  49. intent.setData(Uri.parse('content://media/internal/images/media'))
  50. # TODO setType(Image)?
  51. currentActivity.startActivityForResult(intent, RESULT_LOAD_IMAGE)