Kivy – Receiving Android Intents

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()
            file_uri= intent_data.toString() # isn't Java awesome?
        except AttributeError:
            file_uri = None
        if file_uri is None:
            return # give up
            if file_uri[:7]=="file://":
                self.uiwidget.load(path="",  filename=url2pathname(file_uri[7:]))
                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)

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.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: