Flutter实战之坑——按返回键回到手机桌面不退出app
原理:在main里监听最外层返回键,然后通讯原生,执行 安卓文件里
新建一个
入口文件
moveTaskToBack(false)
回到手机桌面不退出app安卓文件里 MainActivity.java
import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; import android.view.KeyEvent; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; public class MainActivity extends FlutterActivity { //通讯名称,回到手机桌面 private final String CHANNEL = "android/back/desktop"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) { if (methodCall.method.equals("backDesktop")) { result.success(true); moveTaskToBack(false); } } } ); } }
新建一个 android_back_desktop.dart
import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; class AndroidBackTop { //初始化通信管道-设置退出到手机桌面 static const String CHANNEL = "android/back/desktop"; //设置回退到手机桌面 static Future<bool> backDeskTop() async { final platform = MethodChannel(CHANNEL); //通知安卓返回,到手机桌面 try { final bool out = await platform.invokeMethod('backDesktop'); if (out) debugPrint('返回到桌面'); } on PlatformException catch (e) { debugPrint("通信失败(设置回退到安卓手机桌面:设置失败)"); print(e.toString()); } return Future.value(false); } }
入口文件 main.dart
import 'package:flutter_smart_park/untils/android_back_desktop.dart'; export 'package:common_utils/common_utils.dart'; void main() async { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Provide<ConfigModel>( builder: (context, child, configModel) { return MaterialApp( title: 'test', debugShowCheckedModeBanner: false, home: WillPopScope( onWillPop: () async { AndroidBackTop.backDeskTop(); //设置为返回不退出app return false; //一定要return false }, child: Text("Test"), ), ); }, ); } }
End
老铁们,来个素质三连呗!!!
欢迎关注我的博客
相关推荐
chenjinlong 2020-06-04
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30