Android APP打开flutter app并传递参数

1 flutter Android端配置

1.1 manifest 配置修改

<activity
    android:name=".MainActivity"
    android:exported="true"
    android:launchMode="singleTop"
    android:theme="@style/LaunchTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize">
    <!-- Specifies an Android theme to apply to this Activity as soon as
         the Android process has started. This theme is visible to the user
         while the Flutter UI initializes. After that, this theme continues
         to determine the Window background behind the Flutter UI. -->
    <meta-data
      android:name="io.flutter.embedding.android.NormalTheme"
      android:resource="@style/NormalTheme"
      />
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
        <!-- 添加如下代码 -->
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

1.2 在Android源代码的mainActivity为如下代码

package com.swan.flutter_framework

import android.os.Bundle
import io.flutter.plugin.common.MethodChannel
import io.flutter.embedding.android.FlutterActivity

class MainActivity : FlutterActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        //FlutterMain.startInitialization(this);
        super.onCreate(savedInstanceState)

       // GeneratedPluginRegistrant.registerWith(FlutterEngine(this)) // here is the error: Type mismatch. Required: FlutterEngine! Found: MainActivity
        //接收第三方app调运参数并且传递给flutter
        MethodChannel(flutterEngine?.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == InvokeMethod) {
                val greetings = successNativeCode()
                result.success(greetings)
            }
        }
    }

    private fun successNativeCode(): String {
        return "我是android原生跑过来的数据=>${intent.getStringExtra("test")}"
    }

    companion object {
        private const val CHANNEL = "com.swan.shareData"
        private const val InvokeMethod = "shareData"
    }
}

1.3 在要接受回传内容的dart文件中这样写

getSharedText() async {
  const String CHANNEL = "com.swan.shareData"; //这儿要与MethodChannel(flutterEngine?.dartExecutor, CHANNEL)中CHANNEL名称一致
  const String invokeMethod = "shareData"; //这儿要与 call.method == invokeMethod中invokeMethod名称一致
  var channel = const MethodChannel(CHANNEL);
  var result = await channel.invokeMethod(invokeMethod);
  ToastUtils.showToast("message=>$result");
  print('message=>$result');
}

1.4 源代码

  • android端
package com.swan.flutter_framework

import android.os.Bundle
import io.flutter.plugin.common.MethodChannel
import io.flutter.embedding.android.FlutterActivity

class MainActivity : FlutterActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        //FlutterMain.startInitialization(this);
        super.onCreate(savedInstanceState)

       // GeneratedPluginRegistrant.registerWith(FlutterEngine(this)) // here is the error: Type mismatch. Required: FlutterEngine! Found: MainActivity
        //接收第三方app调运参数并且传递给flutter
        MethodChannel(flutterEngine?.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == InvokeMethod) {
                val greetings = successNativeCode()
                result.success(greetings)
            }
        }
    }

    private fun successNativeCode(): String {
        return "我是android原生跑过来的数据=>${intent.getStringExtra("test")}"
    }

    companion object {
        private const val CHANNEL = "com.swan.shareData"
        private const val InvokeMethod = "shareData"
    }
}
  • dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_framework/app/navigator/my_bottom_app_bar.dart';
import 'package:flutter_framework/app/pages/first_guild_page.dart';

/// @Description 应用启动闪屏页
/// @Author swan
/// @Date 2021/12/30 9:37 上午
///
class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

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

class _IndexPageState extends State<IndexPage> with ProtocolModel,CheckUpdateUtil{
    getSharedText() async {
      const String CHANNEL = "com.swan.shareData"; //这儿要与MethodChannel(flutterEngine?.dartExecutor, CHANNEL)中CHANNEL名称一致
      const String invokeMethod = "shareData"; //这儿要与 call.method == invokeMethod中invokeMethod名称一致
      var channel = const MethodChannel(CHANNEL);
      var result = await channel.invokeMethod(invokeMethod);
      ToastUtils.showToast("message=>$result");
      print('message=>$result');
    }
  // 页面的初始化函数
  @override
  void initState() {
    super.initState();
    // 1 检查权限
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      // 2 用户权限和隐私政策
      initDataNext();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Image.asset(Res.welcome),
      ),
    );
  }

  /// 初始化工具类
  Future<void> initDataNext() async {
    getSharedText();
  }
}

2 打开APP调用代码

Intent intent = new Intent();
//参数:包名,要打开的类名
intent.setClassName("com.swan.flutter_framework","com.swan.fluter_framework.MainActivity");
intent.putExtra("test","test");
startActivity(intent);

版权声明:本文为qq_30192407原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。