Starting Kivy service on bootup (Android)

dessant edited this page Dec 4, 2016 · 9 revisions
Clone this wiki locally

Goal: to start a Kivy service on bootup.

I started with this as a sample app+service: https://blog.kivy.org/2014/01/building-a-background-application-on-android-with-kivy/ and emptied the kv string so it has no gui.

We need to listen to the boot complete event in Android, so your build must have permission = RECEIVE_BOOT_COMPLETED.

A BroadcastReceiver is required to listen to this event. As there is no way that I know of for the build to input such a receiver in the AndroidManifest.xml , you need to alter AndroidManifest.tmpl.xml with the following as a direct child of <application>:

<receiver android:name=".MyBroadcastReceiver" android:enabled="true" >
    <intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /></intent-filter>
</receiver>

then build will output it into AndroidManifest.xml anyways. Note the "." in front of "MyBroadcastReceiver" tells java that it belongs to the package in question.

Because on boot up there is no Python interpreter, the BroadcastReceiver cannot be coded in Python and adb logcat will report Android unable to load the Java class version of it. So it must be written in java. Here is all you need - MyBroadcastReceiver.java :

package org.myproject.myapp;  
import android.content.BroadcastReceiver;  
import android.content.Intent;  
import android.content.Context;  
import org.renpy.android.PythonActivity;  
public class MyBroadcastReceiver extends BroadcastReceiver {   
   public void onReceive(Context context, Intent intent) {   
         Intent ix = new Intent(context,PythonActivity.class);   
         ix.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
         context.startActivity(ix);    
    }      
}  

where org.myproject.myapp is the package in question specified in your build parameters. Note that FLAG_ACTIVITY_NEW_TASK must be used as we are starting from boot and our app hasn't started yet. Place the java file in android/python-for-android/dist/default/src.

That's it. Just run the build with the RECEIVE_BOOT_COMPLETED permission and the needed AndroidManifest.xml will be created with the tag as stated above, and you should also see your java file getting compiled.

Thanks to "kived" for all the help on this one, which made it all possible.

p.s.: any improvements to the above are welcome! Thank you.