Skip to content

Commit 09b66cc

Browse files
committed
Add process termination support for Android plugin
Introduces a 'terminate' method to the Android plugin and Dart interface, allowing the app to kill its process for a clean restart. Also disables GIL management in _withGIL due to potential issues with embedded CPython state after Dart isolate restarts.
1 parent 2776a74 commit 09b66cc

File tree

3 files changed

+25
-6
lines changed

3 files changed

+25
-6
lines changed

src/serious_python_android/android/src/main/java/com/flet/serious_python_android/AndroidPlugin.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
import androidx.annotation.NonNull;
66
import android.system.Os;
77
import android.content.Intent;
8+
import android.os.Handler;
9+
import android.os.Looper;
10+
import android.os.Process;
811

912
import io.flutter.embedding.engine.plugins.FlutterPlugin;
1013
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
@@ -80,6 +83,13 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
8083
} catch (Exception e) {
8184
result.error("Error", e.getMessage(), null);
8285
}
86+
} else if (call.method.equals("terminate")) {
87+
// Terminate the process shortly after responding to Dart.
88+
result.success(null);
89+
new Handler(Looper.getMainLooper()).postDelayed(
90+
() -> Process.killProcess(Process.myPid()),
91+
100
92+
);
8393
} else {
8494
result.notImplemented();
8595
}

src/serious_python_android/lib/serious_python_android.dart

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,12 @@ class SeriousPythonAndroid extends SeriousPythonPlatform {
9595
return runPythonProgramFFI(
9696
sync ?? false, "libpython3.12.so", appPath, script ?? "");
9797
}
98+
99+
@override
100+
void terminate() {
101+
// CPython is embedded in-process; after Flutter engine/Dart isolate restarts,
102+
// native CPython state (including the GIL) can be left in a bad state.
103+
// Killing the process is the most reliable way to guarantee a clean start.
104+
methodChannel.invokeMethod<String>('terminate');
105+
}
98106
}

src/serious_python_android/lib/src/cpython.dart

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,13 @@ void _debug(String message) {
5353
}
5454

5555
T _withGIL<T>(CPython cpython, T Function() action) {
56-
final gil = cpython.PyGILState_Ensure();
57-
try {
58-
return action();
59-
} finally {
60-
cpython.PyGILState_Release(gil);
61-
}
56+
// final gil = cpython.PyGILState_Ensure();
57+
// try {
58+
// return action();
59+
// } finally {
60+
// cpython.PyGILState_Release(gil);
61+
// }
62+
return action();
6263
}
6364

6465
Future<String> runPythonProgramFFI(bool sync, String dynamicLibPath,

0 commit comments

Comments
 (0)