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

老铁们,来个素质三连呗!!!
欢迎关注我的博客

相关推荐