flet-android-background 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ build/
4
+ evidence/
5
+ *.egg-info/
6
+ .pytest_cache/
7
+ .dart_tool/
8
+ .flutter-plugins-dependencies
9
+ tests/flutter/pubspec.lock
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Stoica
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: flet-android-background
3
+ Version: 0.0.1
4
+ Summary: Experimental foreground tasks for Flet on Android
5
+ Project-URL: Homepage, https://github.com/alex-stoica/flet-android-background
6
+ Project-URL: Repository, https://github.com/alex-stoica/flet-android-background
7
+ Project-URL: Issues, https://github.com/alex-stoica/flet-android-background/issues
8
+ Author-email: Alex Stoica <alexstoica@protonmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Requires-Python: >=3.11
13
+ Requires-Dist: flet==1.0.3
14
+ Description-Content-Type: text/markdown
15
+
16
+ # flet-android-background
17
+
18
+ Experimental Flet Android tasks; one owns the foreground service.
19
+ Locking permits continued execution; Android restrictions still apply.
20
+ Dismissal or runtime loss stops the service. Process death has no recovery.
21
+
22
+ Install the wheel with pip. Add `BackgroundTask` to your Flet app, then
23
+ `await task.start(work)` or `await task.stop()`.
24
+
25
+ Before building the generated Flutter project:
26
+
27
+ ```python
28
+ from flet_android_background.android import configure_android_project
29
+
30
+ configure_android_project(path, service_type="dataSync")
31
+ ```
32
+
33
+ Supported types: `dataSync`, `shortService`, `specialUse`. The latter requires
34
+ an app-specific `subtype` explanation. Android time limits apply.
@@ -0,0 +1,19 @@
1
+ # flet-android-background
2
+
3
+ Experimental Flet Android tasks; one owns the foreground service.
4
+ Locking permits continued execution; Android restrictions still apply.
5
+ Dismissal or runtime loss stops the service. Process death has no recovery.
6
+
7
+ Install the wheel with pip. Add `BackgroundTask` to your Flet app, then
8
+ `await task.start(work)` or `await task.stop()`.
9
+
10
+ Before building the generated Flutter project:
11
+
12
+ ```python
13
+ from flet_android_background.android import configure_android_project
14
+
15
+ configure_android_project(path, service_type="dataSync")
16
+ ```
17
+
18
+ Supported types: `dataSync`, `shortService`, `specialUse`. The latter requires
19
+ an app-specific `subtype` explanation. Android time limits apply.
@@ -0,0 +1,22 @@
1
+ [project]
2
+ name = "flet-android-background"
3
+ version = "0.0.1"
4
+ description = "Experimental foreground tasks for Flet on Android"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [{name = "Alex Stoica", email = "alexstoica@protonmail.com"}]
8
+ requires-python = ">=3.11"
9
+ dependencies = ["flet==1.0.3"]
10
+ classifiers = ["Development Status :: 3 - Alpha"]
11
+
12
+ [project.urls]
13
+ Homepage = "https://github.com/alex-stoica/flet-android-background"
14
+ Repository = "https://github.com/alex-stoica/flet-android-background"
15
+ Issues = "https://github.com/alex-stoica/flet-android-background/issues"
16
+
17
+ [build-system]
18
+ requires = ["hatchling<1.32"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/flet_android_background", "src/flutter"]
@@ -0,0 +1,93 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable
3
+
4
+ from .service import ForegroundService
5
+
6
+ Callback = Callable[[], Awaitable[None]]
7
+
8
+
9
+ class BackgroundTask:
10
+ """Run one cooperative task. Process death ends execution without restart."""
11
+
12
+ def __init__(self, service: ForegroundService | None = None):
13
+ self.service = service or ForegroundService()
14
+ self.service.on_stopped = self._stopped
15
+ self.error: Exception | None = None
16
+ self._task: asyncio.Task[None] | None = None
17
+ self._work: asyncio.Task[None] | None = None
18
+ self._lock = asyncio.Lock()
19
+
20
+ @property
21
+ def running(self) -> bool:
22
+ return self._task is not None and not self._task.done()
23
+
24
+ async def start(self, work: Callback, *, on_stop: Callback | None = None,
25
+ **notification) -> bool:
26
+ """Start once after notification permission; duplicates return False."""
27
+ async with self._lock:
28
+ if self.running:
29
+ return False
30
+ self.error = None
31
+ starting = asyncio.create_task(self._start_native(notification))
32
+ try:
33
+ failure = await asyncio.shield(starting)
34
+ except asyncio.CancelledError:
35
+ self._task = asyncio.create_task(self._rollback(starting))
36
+ await asyncio.shield(self._task)
37
+ raise
38
+ if failure is not None:
39
+ raise failure
40
+ self._work = asyncio.create_task(self._invoke(work))
41
+ self._task = asyncio.create_task(self._run(self._work, on_stop))
42
+ return True
43
+
44
+ async def _invoke(self, work: Callback):
45
+ await work()
46
+
47
+ async def _start_native(self, notification):
48
+ try:
49
+ await self.service.start_foreground_service(**notification)
50
+ except Exception as exc:
51
+ return exc
52
+
53
+ async def _rollback(self, starting):
54
+ try:
55
+ self.error = await starting
56
+ if self.error is None:
57
+ await self.service.stop_foreground_service()
58
+ except Exception as exc:
59
+ self.error = exc
60
+
61
+ async def _run(self, work: asyncio.Task[None], on_stop: Callback | None):
62
+ try:
63
+ await work
64
+ except asyncio.CancelledError:
65
+ pass
66
+ except Exception as exc:
67
+ self.error = exc
68
+ finally:
69
+ try:
70
+ if on_stop is not None:
71
+ await on_stop()
72
+ except Exception as exc:
73
+ self.error = self.error or exc
74
+ finally:
75
+ try:
76
+ await self.service.stop_foreground_service()
77
+ except Exception as exc:
78
+ self.error = self.error or exc
79
+
80
+ async def stop(self) -> None:
81
+ """Cancel work and await cleanup once."""
82
+ async with self._lock:
83
+ if self.running:
84
+ if self._work is not None:
85
+ self._work.cancel()
86
+ await asyncio.shield(self._task)
87
+
88
+ async def _stopped(self, event):
89
+ async with self._lock:
90
+ if event.data == self.service._owner and self.running:
91
+ if self._work is not None:
92
+ self._work.cancel()
93
+ await asyncio.shield(self._task)
@@ -0,0 +1,43 @@
1
+ from pathlib import Path
2
+ import xml.etree.ElementTree as ET
3
+
4
+ ANDROID = "http://schemas.android.com/apk/res/android"
5
+ NAME = f"{{{ANDROID}}}name"
6
+ SERVICE = "dev.alexstoica.background.TaskService"
7
+ TYPES = {"dataSync": "DATA_SYNC", "shortService": None, "specialUse": "SPECIAL_USE"}
8
+
9
+
10
+ def configure_android_project(project: str | Path, *, service_type: str,
11
+ subtype: str = "") -> None:
12
+ """Declare the app's foreground purpose before building its generated Flutter project."""
13
+ if service_type not in TYPES:
14
+ raise ValueError(f"service_type must be one of {tuple(TYPES)}")
15
+ if service_type == "specialUse" and not subtype.strip():
16
+ raise ValueError("specialUse requires an app-specific subtype explanation")
17
+ path = Path(project) / "android/app/src/main/AndroidManifest.xml"
18
+ ET.register_namespace("android", ANDROID)
19
+ ET.register_namespace("tools", "http://schemas.android.com/tools")
20
+ tree = ET.parse(path, parser=ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
21
+ manifest = tree.getroot()
22
+ application = manifest.find("application")
23
+ if application is None:
24
+ raise ValueError("Android manifest has no application")
25
+ service = next((s for s in application.findall("service") if s.get(NAME) == SERVICE), None)
26
+ if service is None:
27
+ service = ET.SubElement(application, "service", {NAME: SERVICE})
28
+ service.set(f"{{{ANDROID}}}foregroundServiceType", service_type)
29
+ service.set(f"{{{ANDROID}}}exported", "false")
30
+ for prop in list(service.findall("property")):
31
+ if prop.get(NAME) == "android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE":
32
+ service.remove(prop)
33
+ if service_type == "specialUse":
34
+ ET.SubElement(service, "property", {
35
+ NAME: "android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE",
36
+ f"{{{ANDROID}}}value": subtype.strip(),
37
+ })
38
+ suffix = TYPES[service_type]
39
+ if suffix:
40
+ permission = f"android.permission.FOREGROUND_SERVICE_{suffix}"
41
+ if not any(p.get(NAME) == permission for p in manifest.findall("uses-permission")):
42
+ ET.SubElement(manifest, "uses-permission", {NAME: permission})
43
+ tree.write(path, encoding="utf-8", xml_declaration=True)
@@ -0,0 +1,25 @@
1
+ import flet as ft
2
+
3
+
4
+ @ft.control("flet_android_background")
5
+ class ForegroundService(ft.Service):
6
+ on_stopped: ft.ControlEventHandler | None = None
7
+ _owner: str | None = None
8
+
9
+ async def _call(self, method, **arguments):
10
+ result = await self._invoke_method(method_name=method, arguments=arguments)
11
+ if isinstance(result, dict) and "error" in result:
12
+ raise RuntimeError(result["error"])
13
+ return result
14
+
15
+ async def request_permissions(self) -> bool:
16
+ return await self._call("permission")
17
+
18
+ async def start_foreground_service(self, *, notification_id=1,
19
+ title="Background task", body="Running"):
20
+ if notification_id <= 0:
21
+ raise ValueError("notification_id must be positive")
22
+ self._owner = await self._call("start", id=notification_id, title=title, body=body)
23
+
24
+ async def stop_foreground_service(self):
25
+ await self._call("stop")
@@ -0,0 +1,13 @@
1
+ group = "dev.alexstoica.background"
2
+ version = "0.0.1"
3
+ apply plugin: "com.android.library"
4
+
5
+ android {
6
+ namespace = "dev.alexstoica.background"
7
+ compileSdk = 36
8
+ defaultConfig { minSdk = 24 }
9
+ compileOptions {
10
+ sourceCompatibility = JavaVersion.VERSION_17
11
+ targetCompatibility = JavaVersion.VERSION_17
12
+ }
13
+ }
@@ -0,0 +1,8 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
3
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
4
+ <application>
5
+ <service android:name="dev.alexstoica.background.TaskService"
6
+ android:exported="false" />
7
+ </application>
8
+ </manifest>
@@ -0,0 +1,133 @@
1
+ package dev.alexstoica.background;
2
+
3
+ import android.Manifest;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+ import android.content.pm.PackageManager;
7
+ import android.os.Build;
8
+ import io.flutter.embedding.engine.plugins.FlutterPlugin;
9
+ import io.flutter.embedding.engine.plugins.activity.ActivityAware;
10
+ import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
11
+ import io.flutter.plugin.common.MethodCall;
12
+ import io.flutter.plugin.common.MethodChannel;
13
+ import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener;
14
+ import java.util.ArrayList;
15
+
16
+ public class BackgroundPlugin implements FlutterPlugin, ActivityAware,
17
+ MethodChannel.MethodCallHandler, RequestPermissionsResultListener {
18
+ private Context context;
19
+ private MethodChannel channel;
20
+ private ActivityPluginBinding binding;
21
+ private MethodChannel.Result permission;
22
+ private MethodChannel.Result starting;
23
+ private final ArrayList<MethodChannel.Result> stopping = new ArrayList<>();
24
+ private String token;
25
+ private static final int REQUEST = 7141;
26
+
27
+ @Override public void onAttachedToEngine(FlutterPluginBinding engine) {
28
+ context = engine.getApplicationContext();
29
+ channel = new MethodChannel(engine.getBinaryMessenger(), "flet_android_background");
30
+ channel.setMethodCallHandler(this);
31
+ }
32
+
33
+ @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) {
34
+ try {
35
+ switch (call.method) {
36
+ case "permission":
37
+ if (Build.VERSION.SDK_INT < 33 || context.checkSelfPermission(
38
+ Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
39
+ result.success(true);
40
+ } else if (binding == null || permission != null) {
41
+ result.error("permission", "No activity or permission request already pending", null);
42
+ } else {
43
+ permission = result;
44
+ binding.getActivity().requestPermissions(
45
+ new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST);
46
+ }
47
+ break;
48
+ case "start":
49
+ if (TaskService.owner != null) {
50
+ result.error("running", "A background task already owns this service", null);
51
+ break;
52
+ }
53
+ Intent intent = new Intent(context, TaskService.class)
54
+ .putExtra("id", ((Number) call.argument("id")).intValue())
55
+ .putExtra("title", (String) call.argument("title"))
56
+ .putExtra("body", (String) call.argument("body"));
57
+ token = call.argument("owner");
58
+ if (token == null) throw new IllegalArgumentException("Missing service owner");
59
+ TaskService.owner = this;
60
+ starting = result;
61
+ try {
62
+ if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent);
63
+ else context.startService(intent);
64
+ } catch (Exception error) {
65
+ TaskService.owner = null;
66
+ onStarted(error);
67
+ }
68
+ break;
69
+ case "stop":
70
+ if (TaskService.owner != this || !token.equals(call.argument("owner"))) {
71
+ result.success(null);
72
+ } else {
73
+ stopping.add(result);
74
+ context.stopService(new Intent(context, TaskService.class));
75
+ }
76
+ break;
77
+ default:
78
+ result.notImplemented();
79
+ }
80
+ } catch (Exception error) {
81
+ result.error("native", error.toString(), null);
82
+ }
83
+ }
84
+
85
+ void onStarted(Exception error) {
86
+ if (starting == null) return;
87
+ MethodChannel.Result result = starting;
88
+ starting = null;
89
+ if (error == null) result.success(null);
90
+ else result.error("start", error.toString(), null);
91
+ }
92
+
93
+ void onStopped() {
94
+ onStarted(new IllegalStateException("Service stopped during startup"));
95
+ if (channel != null) channel.invokeMethod("stopped", token);
96
+ token = null;
97
+ for (MethodChannel.Result result : stopping) result.success(null);
98
+ stopping.clear();
99
+ }
100
+
101
+ @Override public boolean onRequestPermissionsResult(int code, String[] names, int[] grants) {
102
+ if (code != REQUEST || permission == null) return false;
103
+ permission.success(grants.length > 0 && grants[0] == PackageManager.PERMISSION_GRANTED);
104
+ permission = null;
105
+ return true;
106
+ }
107
+
108
+ @Override public void onAttachedToActivity(ActivityPluginBinding activity) {
109
+ binding = activity;
110
+ binding.addRequestPermissionsResultListener(this);
111
+ }
112
+ @Override public void onDetachedFromActivity() {
113
+ if (binding != null) binding.removeRequestPermissionsResultListener(this);
114
+ binding = null;
115
+ if (permission != null) {
116
+ permission.error("activity", "Activity detached during permission request", null);
117
+ permission = null;
118
+ }
119
+ }
120
+ @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); }
121
+ @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activity) {
122
+ onAttachedToActivity(activity);
123
+ }
124
+ @Override public void onDetachedFromEngine(FlutterPluginBinding engine) {
125
+ onDetachedFromActivity();
126
+ channel.setMethodCallHandler(null);
127
+ channel = null;
128
+ if (TaskService.owner == this) {
129
+ onStopped();
130
+ context.stopService(new Intent(context, TaskService.class));
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,62 @@
1
+ package dev.alexstoica.background;
2
+
3
+ import android.app.Notification;
4
+ import android.app.NotificationChannel;
5
+ import android.app.NotificationManager;
6
+ import android.app.PendingIntent;
7
+ import android.app.Service;
8
+ import android.content.Intent;
9
+ import android.os.Build;
10
+ import android.os.IBinder;
11
+
12
+ public class TaskService extends Service {
13
+ static BackgroundPlugin owner;
14
+ private static final String CHANNEL = "python_background";
15
+
16
+ @Override public int onStartCommand(Intent intent, int flags, int startId) {
17
+ if (owner == null || intent == null || "stop".equals(intent.getAction())) {
18
+ stopSelf();
19
+ return START_NOT_STICKY;
20
+ }
21
+ Exception failure = null;
22
+ try {
23
+ Notification.Builder builder;
24
+ if (Build.VERSION.SDK_INT >= 26) {
25
+ getSystemService(NotificationManager.class).createNotificationChannel(
26
+ new NotificationChannel(CHANNEL, "Background tasks", NotificationManager.IMPORTANCE_LOW));
27
+ builder = new Notification.Builder(this, CHANNEL);
28
+ } else {
29
+ builder = new Notification.Builder(this);
30
+ }
31
+ PendingIntent stop = PendingIntent.getService(this, 0,
32
+ new Intent(this, TaskService.class).setAction("stop"), PendingIntent.FLAG_IMMUTABLE);
33
+ Intent launch = getPackageManager().getLaunchIntentForPackage(getPackageName());
34
+ builder.setContentTitle(intent.getStringExtra("title"))
35
+ .setContentText(intent.getStringExtra("body"))
36
+ .setSmallIcon(getApplicationInfo().icon).setOngoing(true)
37
+ .addAction(new Notification.Action.Builder(null, "Stop", stop).build());
38
+ if (launch != null) builder.setContentIntent(PendingIntent.getActivity(
39
+ this, 0, launch, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
40
+ startForeground(intent.getIntExtra("id", 1), builder.build());
41
+ } catch (Exception error) {
42
+ failure = error;
43
+ stopSelf();
44
+ }
45
+ owner.onStarted(failure);
46
+ return START_NOT_STICKY;
47
+ }
48
+
49
+ @Override public void onTaskRemoved(Intent intent) { stopSelf(); }
50
+ @Override public void onTimeout(int startId) { stopSelf(); }
51
+ @Override public void onTimeout(int startId, int type) { stopSelf(); }
52
+
53
+ @Override public void onDestroy() {
54
+ BackgroundPlugin previous = owner;
55
+ owner = null;
56
+ stopForeground(STOP_FOREGROUND_REMOVE);
57
+ if (previous != null) previous.onStopped();
58
+ super.onDestroy();
59
+ }
60
+
61
+ @Override public IBinder onBind(Intent intent) { return null; }
62
+ }
@@ -0,0 +1,62 @@
1
+ import 'package:flet/flet.dart';
2
+ import 'package:flutter/services.dart';
3
+
4
+ class Extension extends FletExtension {
5
+ @override
6
+ FletService? createService(Control control) =>
7
+ control.type == 'flet_android_background'
8
+ ? BackgroundService(control: control)
9
+ : null;
10
+ }
11
+
12
+ class BackgroundService extends FletService {
13
+ BackgroundService({required super.control});
14
+ static const channel = MethodChannel('flet_android_background');
15
+ static BackgroundService? owner;
16
+ static int sequence = 0;
17
+ String? token;
18
+
19
+ @override
20
+ void init() {
21
+ super.init();
22
+ control.addInvokeMethodListener(invoke);
23
+ channel.setMethodCallHandler((call) async {
24
+ final active = owner;
25
+ if (call.method == 'stopped' && active?.token == call.arguments) {
26
+ owner = null;
27
+ active?.token = null;
28
+ active?.control.triggerEvent('stopped', call.arguments);
29
+ }
30
+ });
31
+ }
32
+
33
+ Future<dynamic> invoke(String method, dynamic arguments) async {
34
+ if (method == 'start') {
35
+ if (owner != null) return {'error': 'A background task already owns this service'};
36
+ owner = this;
37
+ token = '${DateTime.now().microsecondsSinceEpoch}-${sequence++}';
38
+ } else if (method == 'stop' && owner != this) {
39
+ return null;
40
+ }
41
+ try {
42
+ final requested = token;
43
+ final result = await channel.invokeMethod(method, {...?arguments, 'owner': token});
44
+ return method == 'start' ? requested : result;
45
+ } on PlatformException catch (error) {
46
+ if (method == 'start' && owner == this) {
47
+ owner = null;
48
+ token = null;
49
+ }
50
+ return {'error': error.message ?? error.code};
51
+ }
52
+ }
53
+
54
+ @override
55
+ void dispose() {
56
+ control.removeInvokeMethodListener(invoke);
57
+ if (owner == this) {
58
+ invoke('stop', <String, dynamic>{});
59
+ }
60
+ super.dispose();
61
+ }
62
+ }
@@ -0,0 +1,17 @@
1
+ name: flet_android_background
2
+ description: Foreground task lifecycle for Flet Android apps
3
+ version: 0.0.1
4
+ publish_to: none
5
+ environment:
6
+ sdk: '>=3.12.0 <4.0.0'
7
+ flutter: '>=3.44.8'
8
+ dependencies:
9
+ flutter:
10
+ sdk: flutter
11
+ flet: 1.0.3
12
+ flutter:
13
+ plugin:
14
+ platforms:
15
+ android:
16
+ package: dev.alexstoica.background
17
+ pluginClass: BackgroundPlugin