程序员

Flutter 返回键禁止退出App和双击退出方法整理

2020-11-20  本文已影响0人  八怪不姓丑

一、按返回键禁止退出

适用于即时通讯项目

1、先在lib下新建文件

android_back_desktop.dart


import 'package:flutter/cupertino.dart';
import 'package:flutter/services.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);
  }
}
2、在要拦截返回的页面使用 WillPopScope
  Widget build(BuildContext context) {
    // TODO: implement build
    return WillPopScope(
      onWillPop: _onBackPressed,
      child: Container()
    );
  }

  Future<bool> _onBackPressed() async {
    AndroidBackTop.backDeskTop();  //设置为返回不退出app
    return false;
  }
3、修改 android 目录下 MainActivity

⚠️ 注意,根据 flutter sdk 版本和开发语言(Java、kotlin)不同,方式可能有差异
新版本无法直接使用 getFlutterView() 改为 getFlutterEngine().getDartExecutor().getBinaryMessenger()
方法一:
也是百度最多的一种,新版已经不用了

    private final String CHANNEL = "android/back/desktop";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                (methodCall, result) -> {
                    if (methodCall.method.equals("backDesktop")) {
                        result.success(true);
                        moveTaskToBack(false);
                    }
                }
        );
 
    }

方法二(kotlin):


import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant.*
 
class MainActivity: FlutterActivity() {
    private val CHANNEL = "android/back/desktop"
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        registerWith(flutterEngine);
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { methodCall, result ->
            if (methodCall.method == "backDesktop") {
                result.success(true)
                moveTaskToBack(false)
            }
        }
    }
}

二、再按一次退出app

  int lastExitTime = 0;
  Future<bool> _onBackPressed() async {
     int nowExitTime = DateTime.now().millisecondsSinceEpoch;
     if (nowExitTime - lastExitTime > 2000) {
       lastExitTime = nowExitTime;
       ToastUtils.show(S.of(context).g_key_289);
       return await Future.value(false);
     }else {
       exit(0);
       return await Future.value(true);
     }
  }
上一篇下一篇

猜你喜欢

热点阅读