等效于颤振中的"moveTaskToBack(true)"



当按下后退按钮时,我想让应用程序在后台运行,就像我们按下主页按钮一样。我使用flutter,所以我需要一个相当于android中的"moveTaskToBack(true("。

03.2020解决方案

你应该用WillPopScope包装你的脚手架,所以最终的代码应该如下所示:

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(
...
),
);
}

MainActivity(((android/app/src/main/kotlin/{yourProjectId}(中的代码应该如下所示:

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)
}
}
}
}
}

最新更新