Flutter實戰之坑——按返回鍵回到手機桌面不退出app

因禿而強發表於2019-04-23

原理:在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

老鐵們,來個素質三連唄!!! 歡迎關注我的部落格

相關文章