原理:在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"), ), ); }, ); } }
老鐵們,來個素質三連唄!!!
歡迎關注個人博客java