Chapter 5: Writing the First Android Application in Python

You will write a very simplest version of hello world, this application will ask your name and then it will greet you.

img

  1. Copy the following code to greet_app.py on your computer.
    import android
    app = android.Android()

    name = app.dialogGetInput("Enter your name:", "Please enter your name:
    ").result

    app.dialogDismiss()
    app.dialogCreateAlert("Greetings!!!", "Hello %s, how are you?" % name)
    app.dialogSetPositiveButtonText('OK')
    app.dialogShow()
    app.dialogGetResponse().result
    app.dialogDismiss()

2. Goto “platform-tools” directory which is found under the Android SDK directory.

3. Copy (push) the greet_app.py to your Android by running the following command.

$ ./adb push /sdcard/sl4a/scripts/

4. Press the menu button on your Android device or Android emulator, and tap Refresh.

5. greet_app.py will appear in the script listing, tap the greet_app.py script.

6. The SL4A run menu will appear, click the second icon from left.

img

7. A popup will appear asking you for your name, enter your name and click OK.

8. Another popup will appear with a greeting message for you

Congratulations!!! You are done here.
It’s now up to you how you make use of the Android API available via SL4A

Let’s create a simple Hello world application, with one Label and one Button.

  1. Ensure you’ve correctly installed and configured the project as said in the Prerequisites
  2. Create a directory named helloworld:
mkdir helloworld
cd helloworld

• Create a file named main.py, with this content:

img

• Go to the python-for-android directory

• Create a distribution with kivy:

./distribute.sh -m kivy

• Go to the newly created default distribution:

cd dist/default

• Plug your android device, and ensure you can install development application

• Build your hello world application in debug mode:

  1. /build.py --package org.hello.world --name "Hello world" \
  2. --version 1.0 --dir /PATH/TO/helloworld debug installd
  3. Take your device, and start the application!
  4. If something goes wrong, open the logcat by doing:
  5. adb logcat

The final debug APK will be located in bin/hello-world-1.0-debug.apk.

If you want to release your application instead of just making a debug APK, you must:

  1. Generate a non-signed APK:
  2. ./build.py --package org.hello.world --name "Hello world" \
  3. --version 1.0 --dir /PATH/TO/helloworld release

This will create your first hello world android apk.

To capture android logs- options are available kernel logs, adb logcat logs, radio logs for android devices.

Commands-

  • Adb devices
  • Adb logcat
  • Adb shell
  • Adb logcat –radio Many more adb commands are available to debug the Android app .

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?