Flutter在安卓平台保持后台运行

Flutter在安卓平台保持后台运行

现有的中文资料,还在修改MainActivity.java 文件,实际上Google 宣布 Kotlin 取代 Java 成为 Android 官方开发语言,所以flutter的默认入口为MainActivity.kt。

退出系统后还可以在后台运行的实现方法:

1.核心:moveTaskToBack(true),
(/项目名/android/app/src/main/kotlin/包名/MainActivity.kt)

class MainActivity : FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Notifications.createNotificationChannels(this)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        val binaryMessenger = flutterEngine.dartExecutor.binaryMessenger
      
        MethodChannel(binaryMessenger, "life.qdu/app_retain").apply {
            setMethodCallHandler { method, result ->
                if (method.method == "sendToBackground") {
                    moveTaskToBack(true)
                    result.success(null)
                } else {
                    result.notImplemented()
                }
            }
        }
    }
}

2.创建一个AppRetainWidget,当接收到pop事件时,如果不能pop,则会去调用”sendToBackground”方法

class AppRetainWidget extends StatelessWidget {
  const AppRetainWidget({Key key, this.child}) : super(key: key);

  final Widget child;

  final _channel = const MethodChannel('life.qdu/app_retain');

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (Platform.isAndroid) {
          if (Navigator.of(context).canPop()) {
            return true;
          } else {
            _channel.invokeMethod('sendToBackground');
            return false;
          }
        } else {
          return true;
        }
      },
      child: child,
    );
  }
}

3.用上述组件,包裹住你的组件

@override
 Widget build(BuildContext context) {
   return AppRetainWidget(
      child: Scaffold(),
   );
} 
    原文作者:う风尘子
    原文地址: https://blog.csdn.net/weixin_46156477/article/details/116779831
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞