I want to keep the application running in background when pressing the back button, exactly like we press the home button. Im using flutter so i need an equivalent to "moveTaskToBack(true)" in android.
Asked
Active
Viewed 766 times
2
-
This does not solve your question but here some more background information https://stackoverflow.com/questions/41924890/how-do-i-run-code-in-the-background-even-with-the-screen-off – user1462442 Nov 08 '18 at 19:53
1 Answers
2
03.2020 SOLUTION
You should wrap your Scaffold with WillPopScope, so the final code should look like as below:
var _androidAppRetain = MethodChannel("android_app_retain");
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
if (Platform.isAndroid) {
if (Navigator.of(context).canPop()) {
return Future.value(true);
} else {
_androidAppRetain.invokeMethod("sendToBackground");
return Future.value(false);
}
} else {
return Future.value(true);
}
},
child: Scaffold(
...
),
);
}
The code in the MainActivity() (android/app/src/main/kotlin/{yourProjectId}) should look like this:
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "android_app_retain").apply {
setMethodCallHandler { method, result ->
if (method.method == "sendToBackground") {
moveTaskToBack(true)
}
}
}
}
}

Muscler
- 99
- 1
- 7