Skip to content

Commit

Permalink
added --network-security-config, --uses-cleartext-traffic, --activity…
Browse files Browse the repository at this point in the history
…-class-name and --service-class-name input parameters
  • Loading branch information
vesellov committed Oct 19, 2020
1 parent 690dd18 commit 471422a
Show file tree
Hide file tree
Showing 10 changed files with 68 additions and 8 deletions.
18 changes: 18 additions & 0 deletions pythonforandroid/bootstraps/common/build/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,9 @@ def make_package(args):
if not args.activity_launch_mode:
args.activity_launch_mode = ''

# if not args.service_class_name:
# args.service_class_name = 'org.kivy.android.PythonService'

if args.extra_source_dirs:
esd = []
for spec in args.extra_source_dirs:
Expand All @@ -418,6 +421,7 @@ def make_package(args):
service = True

service_names = []
base_service_class = args.service_class_name.split('.')[-1]
for sid, spec in enumerate(args.services):
spec = spec.split(':')
name = spec[0]
Expand All @@ -442,6 +446,7 @@ def make_package(args):
foreground=foreground,
sticky=sticky,
service_id=sid + 1,
base_service_class=base_service_class,
)

# Find the SDK directory and target API
Expand Down Expand Up @@ -478,6 +483,7 @@ def make_package(args):
args.backup_rules = split(args.backup_rules)[1][:-4]

# Render out android manifest:
print("Rendering AndroidManifest.xml...", args)
manifest_path = "src/main/AndroidManifest.xml"
render_args = {
"args": args,
Expand Down Expand Up @@ -778,12 +784,22 @@ def parse_args_and_make_package(args=None):
ap.add_argument('--manifest-placeholders', dest='manifest_placeholders',
default='[:]', help=('Inject build variables into the manifest '
'via the manifestPlaceholders property'))
ap.add_argument('--network-security-config', dest='network_security_config', default='',
help='Add a Network Security Configuration file path to AndroidManifest.xml')
ap.add_argument('--uses-cleartext-traffic', dest='uses_cleartext_traffic', default='',
help='Indicate that app intends to use cleartext network traffic in AndroidManifest.xml')
ap.add_argument('--service-class-name', dest='service_class_name', default='org.kivy.android.PythonService',
help='Use that parameter if you need to implement your own PythonServive Java class')
ap.add_argument('--activity-class-name', dest='activity_class_name', default='org.kivy.android.PythonActivity',
help='The full java class name of the main activity')

# Put together arguments, and add those from .p4a config file:
if args is None:
args = sys.argv[1:]
print('args was empty, set from sys.argv')

def _read_configuration():
print("Looking for p4a configuration file in %r" % os.path.abspath('.p4a'))
if not exists(".p4a"):
return
print("Reading .p4a configuration")
Expand All @@ -793,10 +809,12 @@ def _read_configuration():
for line in lines if not line.startswith("#")]
for line in lines:
for arg in line:
print('Added option: %r' % arg)
args.append(arg)
_read_configuration()

args = ap.parse_args(args)

args.ignore_path = []

if args.name and args.name[0] == '"' and args.name[-1] == '"':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ protected int getServiceId() {
}

protected void doStartForeground(Bundle extras) {
Log.v("python service", "doStartForeground");
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = extras.getString("serviceDescription");
Notification notification;
Expand Down Expand Up @@ -137,6 +138,7 @@ protected void doStartForeground(Bundle extras) {

@Override
public void onDestroy() {
Log.v("python service", "onDestroy");
super.onDestroy();
pythonThread = null;
if (autoRestartService && startIntent != null) {
Expand All @@ -152,17 +154,20 @@ public void onDestroy() {
*/
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.v("python service", "onTaskRemoved");
super.onTaskRemoved(rootIntent);
stopSelf();
}

@Override
public void run(){
Log.v("python service", "run");
String app_root = getFilesDir().getAbsolutePath() + "/app";
File app_root_file = new File(app_root);
PythonUtil.loadLibraries(app_root_file,
new File(getApplicationInfo().nativeLibraryDir));
this.mService = this;
Log.v("python service", "run before nativeStart");
nativeStart(
androidPrivate, androidArgument,
serviceEntrypoint, pythonName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

import android.content.Intent;
import android.content.Context;
import org.kivy.android.PythonService;
import {{ args.service_class_name }};


public class Service{{ name|capitalize }} extends PythonService {
public class Service{{ name|capitalize }} extends {{ base_service_class }} {
{% if sticky %}
@Override
public int startType() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@
android:icon="@drawable/icon"
android:allowBackup="{{ args.allow_backup }}"
{% if args.backup_rules %}android:fullBackupContent="@xml/{{ args.backup_rules }}"{% endif %}
{% if args.network_security_config %}android:networkSecurityConfig="{{ args.network_security_config }}"{% endif %}
{% if args.uses_cleartext_traffic %}android:usesCleartextTraffic="{{ args.uses_cleartext_traffic }}"{% endif %}
android:theme="{{args.android_apptheme}}{% if not args.window %}.Fullscreen{% endif %}"
android:hardwareAccelerated="true" >
android:hardwareAccelerated="true"
>
{% for l in args.android_used_libs %}
<uses-library android:name="{{ l }}" />
{% endfor %}
Expand Down Expand Up @@ -110,7 +113,7 @@
{% endif %}

{% if service or args.launcher %}
<service android:name="org.kivy.android.PythonService"
<service android:name="{{ args.service_class_name }}"
android:process=":pythonservice" />
{% endif %}
{% for name in service_names %}
Expand Down
1 change: 1 addition & 0 deletions pythonforandroid/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ def __init__(self):
self.copy_libs = False

self.activity_class_name = u'org.kivy.android.PythonActivity'
self.service_class_name = u'org.kivy.android.PythonService'

# this list should contain all Archs, it is pruned later
self.archs = (
Expand Down
1 change: 1 addition & 0 deletions pythonforandroid/recipes/android/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def prebuild_arch(self, arch):
'JNI_NAMESPACE': jni_ns,
'ACTIVITY_CLASS_NAME': self.ctx.activity_class_name,
'ACTIVITY_CLASS_NAMESPACE': self.ctx.activity_class_name.replace('.', '/'),
'SERVICE_CLASS_NAME': self.ctx.service_class_name,
}

# create config files for Cython, C and Python
Expand Down
4 changes: 2 additions & 2 deletions pythonforandroid/recipes/android/src/android/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Broadcast receiver bridge

from jnius import autoclass, PythonJavaClass, java_method
from android.config import JAVA_NAMESPACE, JNI_NAMESPACE, ACTIVITY_CLASS_NAME
from android.config import JAVA_NAMESPACE, JNI_NAMESPACE, ACTIVITY_CLASS_NAME, SERVICE_CLASS_NAME


class BroadcastReceiver(object):
Expand Down Expand Up @@ -72,7 +72,7 @@ def stop(self):
def context(self):
from os import environ
if 'PYTHON_SERVICE_ARGUMENT' in environ:
PythonService = autoclass(JAVA_NAMESPACE + '.PythonService')
PythonService = autoclass(SERVICE_CLASS_NAME)
return PythonService.mService
PythonActivity = autoclass(ACTIVITY_CLASS_NAME)
return PythonActivity.mActivity
4 changes: 2 additions & 2 deletions pythonforandroid/recipes/android/src/android/storage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from jnius import autoclass, cast
import os

from android.config import JAVA_NAMESPACE, ACTIVITY_CLASS_NAME
from android.config import ACTIVITY_CLASS_NAME, SERVICE_CLASS_NAME


Environment = autoclass('android.os.Environment')
Expand Down Expand Up @@ -34,7 +34,7 @@ def _get_activity():
activity = PythonActivity.mActivity
if activity is None:
# assume we're running from the background service
PythonService = autoclass(JAVA_NAMESPACE + '.' + 'PythonService')
PythonService = autoclass(SERVICE_CLASS_NAME)
activity = PythonService.mService
return activity

Expand Down
26 changes: 26 additions & 0 deletions pythonforandroid/toolchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,21 @@ def __init__(self):
dest='activity_class_name', default='org.kivy.android.PythonActivity',
help='The full java class name of the main activity')

generic_parser.add_argument(
'--service-class-name',
dest='service_class_name', default='org.kivy.android.PythonService',
help='Full java package name of the PythonService class')

generic_parser.add_argument(
'--network-security-config',
dest='network_security_config', default=None,
help='Add a Network Security Configuration file path to AndroidManifest.xml')

generic_parser.add_argument(
'--uses-cleartext-traffic',
dest='uses_cleartext_traffic', default=None,
help='Indicate that app intends to use cleartext network traffic in AndroidManifest.xml')

generic_parser.add_argument(
'--java-build-tool',
dest='java_build_tool', default='auto',
Expand Down Expand Up @@ -613,6 +628,14 @@ def add_parser(subparsers, *args, **kwargs):
args.unknown_args += ["--with-debug-symbols"]
if hasattr(args, "ignore_setup_py") and args.ignore_setup_py:
args.use_setup_py = False
if hasattr(args, "activity_class_name") and args.activity_class_name != 'org.kivy.android.PythonActivity':
args.unknown_args += ["--activity-class-name", args.activity_class_name]
if hasattr(args, "service_class_name") and args.service_class_name != 'org.kivy.android.PythonService':
args.unknown_args += ["--service-class-name", args.service_class_name]
if hasattr(args, "network_security_config") and args.network_security_config is not None:
args.unknown_args += ["--network-security-config", args.network_security_config]
if hasattr(args, "uses_cleartext_traffic") and args.uses_cleartext_traffic is not None:
args.unknown_args += ["--uses-cleartext-traffic", args.uses_cleartext_traffic]

self.args = args

Expand Down Expand Up @@ -709,6 +732,9 @@ def add_parser(subparsers, *args, **kwargs):
self.ctx.copy_libs = args.copy_libs

self.ctx.activity_class_name = args.activity_class_name
self.ctx.network_security_config = args.network_security_config
self.ctx.uses_cleartext_traffic = args.uses_cleartext_traffic
self.ctx.service_class_name = args.service_class_name

# Each subparser corresponds to a method
command = args.subparser_name.replace('-', '_')
Expand Down
6 changes: 6 additions & 0 deletions tests/test_toolchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ def test_create(self):
'--requirements=python3',
'--dist-name=test_toolchain',
'--activity-class-name=abc.myapp.android.CustomPythonActivity',
'--service-class-name=xyz.myapp.android.CustomPythonService',
'--network-security-config=1',
'--uses-cleartext-traffic=1',
]
with patch_sys_argv(argv), mock.patch(
'pythonforandroid.build.get_available_apis'
Expand All @@ -80,6 +83,9 @@ def test_create(self):
'/tmp/android-ndk/platforms/android-21/arch-arm', True)
tchain = ToolchainCL()
assert tchain.ctx.activity_class_name == 'abc.myapp.android.CustomPythonActivity'
assert tchain.ctx.service_class_name == 'xyz.myapp.android.CustomPythonService'
assert tchain.ctx.network_security_config == '1'
assert tchain.ctx.uses_cleartext_traffic == '1'
assert m_get_available_apis.call_args_list in [
[mock.call('/tmp/android-sdk')], # linux case
[mock.call('/private/tmp/android-sdk')] # macos case
Expand Down

0 comments on commit 471422a

Please sign in to comment.