Flutter学習ノートは戻るボタンを押して直接デスクトップに戻って、APPを退出しません

11974 ワード

Flutterアプリケーションでは、戻るキーを押すたびにデスクトップに戻ると、アプリは自動的に終了します.デスクトップに戻るときにバックグラウンドでアプリケーションを実行できるようにするには、Android原生との通信が必要です
まずはandroidパッケージ下のMainActivityで、修正
package com.example.flutter_app;

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
     
    //    ,      
    private final String CHANNEL = "android/back/desktop";
    //        
    static final String eventBackDesktop = "backDesktop";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);

        initBackToDesktop();
    }

    //           
    private void initBackToDesktop() {
     
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
     
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
     
                        if (methodCall.method.equals(eventBackDesktop)) {
     
                            moveTaskToBack(false);
                            result.success(true);
                        }
                    }
                }
        );
    }
}


次にFlutterのlibの下にandroid_を追加しますback_desktop.dartファイル:
import 'package:flutter/services.dart';

class AndroidBackDesktop{
     
  //    ,      
  static const String CHANNEL = "android/back/desktop";
  //           
  static const String eventBackDesktop = "backDesktop";

  //           
  static Future<bool> backToDesktop() async {
     
    final platform = MethodChannel(CHANNEL);
    //           
    try{
     
      await platform.invokeMethod(eventBackDesktop);
    }
    on PlatformException catch (e){
     
      print("    ,             ");
      print(e.toString());
    }
    return Future.value(false);
  }
}

最後はmain.dartではWillPopScopeパッケージを使用し、onWillpopで通知をデスクトップに戻す方法を呼び出します.
import 'package:flutter/material.dart';
import 'package:flutter_app/android_back_desktop.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
     
  @override
  Widget build(BuildContext context) {
     
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
     
  MyHomePage({
     Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
     
  int _counter = 0;

  void _incrementCounter() {
     
    setState(() {
     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
     
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        ),
        onWillPop: AndroidBackDesktop.backToDesktop);
  }
}


効果: