Kivy – Receiving Android Intents
July 23, 2014 Leave a comment
In theory Kivy has a way to receive intents generated from other apps on Android – it’s the on_new_intent callback hook. To use it you first need to write a method to handle the intent. The method will be passed the intent, but you’re going to have to unpack data from it. What data is to be unpacked and how you go about it will be different depending on the intent. You’ll need to dig into the Android Java docs/stack exchange to get details. This is a sample unpacking of a file uri which has been provided by a file manager app. The file uri is not in a format that Kivy can use so it’s got to first be unescaped (here I use url2pathname from urllib2):
class GridderApp(App): # [stuff deleted] def on_new_intent(self, intent): intent_data = intent.getData() try: file_uri= intent_data.toString() # isn't Java awesome? except AttributeError: file_uri = None if file_uri is None: return # give up else: if file_uri[:7]=="file://": self.uiwidget.load(path="", filename=url2pathname(file_uri[7:])) else: return # again, give up
That’d all be lovely if that’s how it actually worked. Unfortunately on_new_intent seems to be designed on the assumption that it’s being run as the method of a Service not an app. This code won’t work for an app for reasons to be covered in a later post.
After you’ve defined this method you need to bind it:
if __name__ == "__main__": if platform=="android": import android.activity app = GridderApp(file_uri=file_uri) android.activity.bind(on_new_intent=app.on_new_intent)
After which, you’re good to go! Except that apps suffer from a problem with receiving intents – see my next post.
Apparently (as at July 2014) on_new_intent does not work on the application’s first start, so you can’t get (eg) a file uri from an intent if your app has not been run before or has been run, but stopped. I’m told this is a bug so it may be fixed in the future.