Flutter中,解决按下返回键将应用挂起到后台,并不会退出的问题

Flutter中,解决按下返回键将应用挂起到后台,并不会退出的问题

参考地址:传送门

问题:
由于应用中牵扯到了聊天的功能,由于Flutter默认的返回是直接退出APP的,所以需要我们自己特殊配置一下
注意:Flutter在最新的版本中,java代码已经逐渐由kotlin代码替代,所以下面将会展示两个版本的代码来解决这个问题

旧版本Flutter:
第一步:

首先查找到以下路径
在这里插入图片描述
打开这个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);
					}
				}
			}
		);
	}
}

第二步:

创建个Dart文件,文件名自己取,我这里取名为android_back.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);
	}
}

第三步:

首先引入进来你之前写的这个dart文件,在main里监听最外层返回键,然后通讯原生,执行 moveTaskToBack(false) 回到手机桌面不退出app

import 'package:flutter/material.dart';
import 'package:shoppingmall/android_back.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"),
          ),
        );
      },
    );
  }
}
新版本Flutter:

新版本的flutter只是在安卓里的那个文件有所不同,代码已经变为了kotlin的格式,所以,里面的代码我们要写成kotlin的样子
在这里插入图片描述



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

class MainActivity : FlutterActivity() {
    //通讯名称,回到手机桌面
    private val CHANNEL = "android/back/desktop"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegistrant.registerWith(this)
        MethodChannel(flutterView, CHANNEL).setMethodCallHandler { methodCall, result ->
            if (methodCall.method == "backDesktop") {
                result.success(true)
                moveTaskToBack(false)
            }
        }
    }
}



如何结合路由使用??
class _MyAppState extends State<MyApp> {
	int _currentIndex = 0; // 展示下标

  List pageList = [HomePage(), MessagePage(), UserPage()];

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          AndroidBackTop.backDeskTop(); //设置为返回不退出app
          return false; //一定要return false
        },
        child: Scaffold(
        appBar: AppBar(title: Text('头部')),
        body: pageList[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed, //允许多个菜单
          onTap: (index) {
            setState(() {
              this._currentIndex = index;
            });
          },
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('首页')),
            BottomNavigationBarItem(
                icon: Icon(Icons.message), title: Text('消息')),
            BottomNavigationBarItem(icon: Icon(Icons.people), title: Text('用户'))
          ],
        ),
      ),
      );
      
  }
}
额外知识

java代码如何转换成kotlin??? kotlin如何转换成Java????

解决地址


最后只需要运行程序,就可以体验

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值