Python API

The Python for Android project includes a Python module called android which consists of multiple parts that are mostly there to facilitate the use of the Java API.

This module is not designed to be comprehensive. Most of the Java API is also accessible with PyJNIus, so if you can’t find what you need here you can try using the Java API directly instead.

Android (android)


This should be called on a regular basis to check to see if Android expects the application to pause. If it returns true, the app should call android.wait_for_resume(), after storing its state as necessary.


This function should be called after android.check_pause() and returns true. It does not return until Android has resumed from the pause. While in this function, Android may kill the app without further notice.

android.map_key(keycode, keysym)

This maps an android keycode to a python keysym. The android keycodes are available as constants in the android module.

Activity (android.activity)

The default PythonActivity has a observer pattern for onActivityResult and onNewIntent.

android.activity.bind(eventname=callback, ...)

This allows you to bind a callback to an Android event: - on_new_intent is the event associated to the onNewIntent java call - on_activity_result is the event associated to the onActivityResult java call


This method is not thread-safe. Call it in the mainthread of your app. (tips: use kivy.clock.mainthread decorator)

android.activity.unbind(eventname=callback, ...)

Unregister a previously registered callback with bind().


# This example is a snippet from an NFC p2p app implemented with Kivy.

from android import activity

def on_new_intent(self, intent):
    if intent.getAction() != NfcAdapter.ACTION_NDEF_DISCOVERED:
    rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
    if not rawmsgs:
    for message in rawmsgs:
        message = cast(NdefMessage, message)
        payload = message.getRecords()[0].getPayload()
        print 'payload: {}'.format(''.join(map(chr, payload)))

def nfc_enable(self):
    # ...

def nfc_disable(self):
    # ...

Billing (android.billing)

This billing module gives an access to the In-App Billing:

  1. Setup a test account, and get your Public Key

  2. Export your public key:

    export BILLING_PUBKEY="Your public key here"
  3. Setup some In-App product to buy. Let’s say you’ve created a product with the id “org.kivy.gopremium”

  4. In your application, you can use the billing module like this:

    from android.billing import BillingService
    from kivy.clock import Clock
    class MyBillingService(object):
        def __init__(self):
            super(MyBillingService, self).__init__()
            # Start the billing service, and attach our callback
            self.service = BillingService(billing_callback)
            # Start a clock to check billing service message every second
            Clock.schedule_interval(self.service.check, 1)
        def billing_callback(self, action, *largs):
            '''Callback that will receive all the events from the Billing service
            if action == BillingService.BILLING_ACTION_ITEMSCHANGED:
                items = largs[0]
                if 'org.kivy.gopremium' in items:
                    print "Congratulations, you have a premium acess"
                    print "Unfortunately, you don't have premium access"
        def buy(self, sku):
            # Method to buy something.
        def get_purchased_items(self):
            # Return all the items purchased
            return self.service.get_purchased_items()
  5. To initiate an in-app purchase, just call the buy() method:

    # Note: start the service at the start, and never twice!
    bs = MyBillingService()'org.kivy.gopremium')
    # Later, when you get the notification that items have been changed, you
    # can still check all the items you bought:
    print bs.get_purchased_items()
    {'org.kivy.gopremium': {'qt: 1}}
  6. You’ll receive all the notifications about the billing process in the callback.

  7. Last step, create your application with --with-billing $BILLING_PUBKEY:

    ./ ... --with-billing $BILLING_PUBKEY

Broadcast (android.broadcast)

Implementation of the android BroadcastReceiver. You can specify the callback that will receive the broadcast event, and actions or categories filters.

class android.broadcast.BroadcastReceiver


The callback will be called in another thread than the main thread. In that thread, be careful not to access OpenGL or something like that.

__init__(callback, actions=None, categories=None)
  • callback – function or method that will receive the event. Will receive the context and intent as argument.
  • actions – list of strings that represent an action.
  • categories – list of strings that represent a category.

For actions and categories, the string must be in lower case, without the prefix:

# In python: 'headset_plug'

Register the receiver with all the actions and categories, and start handling events.


Unregister the receiver with all the actions and categories, and stop handling events.


class TestApp(App):

    def build(self): = BroadcastReceiver(
            self.on_broadcast, actions=['headset_plug'])
        # ...

    def on_broadcast(self, context, intent):
        extras = intent.getExtras()
        headset_state = bool(extras.get('state'))
        if headset_state:
            print 'The headset is plugged'
            print 'The headset is unplugged'

    # Don't forget to stop and restart the receiver when the app is going
    # to pause / resume mode

    def on_pause(self):
        return True

    def on_resume(self):

Mixer (android.mixer)

The android.mixer module contains a subset of the functionality in found in the pygame.mixer module. It’s intended to be imported as an alternative to pygame.mixer, using code like:

    import pygame.mixer as mixer
except ImportError:
    import android.mixer as mixer

Note that if you’re using the module, you don’t have to do anything, it is all automatic.

The android.mixer module is a wrapper around the Android MediaPlayer class. This allows it to take advantage of any hardware acceleration present, and also eliminates the need to ship codecs as part of an application.

It has several differences with the pygame mixer:

  • The init() and pre_init() methods work, but are ignored - Android chooses appropriate settings automatically.
  • Only filenames and true file objects can be used - file-like objects will probably not work.
  • Fadeout does not work - it causes a stop to occur.
  • Looping is all or nothing, there is no way to choose the number of loops that occur. For looping to work, the android.mixer.periodic() function should be called on a regular basis.
  • Volume control is ignored.
  • End events are not implemented.
  • The object is a class (with static methods on it), rather than a module. Calling methods like should work.

Runnable (android.runnable)

Runnable is a wrapper around the Java Runnable class. This class can be used to schedule a call of a Python function into the PythonActivity thread.


from android.runnable import Runnable

def helloworld(arg):
    print 'Called from PythonActivity with arg:', arg


Or use our decorator:

from android.runnable import run_on_ui_thread

def helloworld(arg):
    print 'Called from PythonActivity with arg:', arg


This can be used to prevent errors like:

  • W/System.err( 9514): java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
  • NullPointerException in ActivityThread.currentActivityThread()


Because the python function is called from the PythonActivity thread, you need to be careful about your own calls.

Service (android.service)

Services of an application are controlled through the class AndroidService.

class android.service.AndroidService(title, description)

Run service/ from the application directory as a service.

  • title (str) – Notification title, default to ‘Python service’
  • description (str) – Notification text, default to ‘Kivy Python service started’

Start the service.

Parameters:arg (str) – Argument to pass to a service, through the environment variable PYTHON_SERVICE_ARGUMENT. Defaults to ‘’

Stop the service.

Application activity part example,

from android import AndroidService


 class ServiceExample(App):


     def start_service(self):
         self.service = AndroidService('Sevice example', 'service is running')
         self.service.start('Hello From Service')

     def stop_service(self):

Application service part example, service/

import os
import time

# get the argument passed
arg = os.getenv('PYTHON_SERVICE_ARGUMENT')

while True:
    # this will print 'Hello From Service' continually, even when the application is switched
    print arg