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);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值