如何将意图传递给Flutter中的MethodChannel

huangapple go评论85阅读模式
英文:

How to pass intent to methodchannel in Flutter

问题

我想通过使用 MethodChannel 将网页 URL 传递给我的应用,但是我的 MethodChannel 总是返回 'null'。

我按照官方文档操作,链接在这里 [如何在 Flutter 中处理来自外部应用程序的传入意图?](https://flutter.dev/docs/get-started/flutter-for/android-devs#what-is-the-equivalent-of-an-intent-in-flutter),以下是我的代码。

// AndroidManifest.xml

```xml
<activity
    android:name=".MainActivity"
    android:launchMode="singleTask"
    android:theme="@style/LaunchTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize">
    <meta-data
      android:name="io.flutter.embedding.android.NormalTheme"
      android:resource="@style/NormalTheme"
      />
    <meta-data
      android:name="io.flutter.embedding.android.SplashScreenDrawable"
      android:resource="@drawable/launch_background"
      />
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

MainActivity.java

public class MainActivity extends FlutterActivity {

  private String sharedText;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // GeneratedPluginRegistrant.registerWith(this);
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
      if ("text/plain".equals(type)) {
        handleSendText(intent); // Handle text being sent
      }
    }

    new MethodChannel(getFlutterView(), "app.channel.shared").setMethodCallHandler(
      new MethodCallHandler() {
        @Override
        public void onMethodCall(MethodCall call, MethodChannel.Result result) {
          if (call.method.contentEquals("getSharedText")) {
            result.success(sharedText);
            sharedText = null;
          }
        }
      });
  }

  void handleSendText(Intent intent) {
    sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
  }
}

main.dart

class TestPage extends StatefulWidget {
  @override
  createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> with WidgetsBindingObserver {
  String url;

  static const channel = const MethodChannel('app.channel.shared');

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    setState(() {
      url = "sample";
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      getChannel();
    }
  }

  void getChannel() async {
    var message = await channel.invokeMethod("getSharedText");
    debugPrint(message);
    setState(() {
      url = message;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text(url),
        ]
      ),
    );
  }
}

我尝试通过 channel.invokeMethod("getSharedText") 获取数据,但它返回 null

我的代码有什么问题吗?


<details>
<summary>英文:</summary>

I want to pass webpage url to my app by using methodchannel, but my methodchannel always returns &#39;null&#39;. 

I followed the official document, which is [How do I handle incoming intents from external applications in Flutter? ](https://flutter.dev/docs/get-started/flutter-for/android-devs#what-is-the-equivalent-of-an-intent-in-flutter), and this is my code .

//AndroidManifest.xml

<activity
android:name=".MainActivity"
android:launchMode="singleTask"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>

</activity>


MainActivity.java

public class MainActivity extends FlutterActivity {

private String sharedText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// GeneratedPluginRegistrant.registerWith(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();

if (Intent.ACTION_SEND.equals(action) &amp;&amp; type != null) {
  if (&quot;text/plain&quot;.equals(type)) {
    handleSendText(intent); // Handle text being sent
  }
}

new MethodChannel(getFlutterView(), &quot;app.channel.shared&quot;).setMethodCallHandler(
  new MethodCallHandler() {
    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
      if (call.method.contentEquals(&quot;getSharedText&quot;)) {
        result.success(sharedText);
        sharedText = null;
      }
    }
  });

}

void handleSendText(Intent intent) {
sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}


main.dart

class TestPage extends StatefulWidget {
@override
createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> with WidgetsBindingObserver {
String url;

static const channel = const MethodChannel('app.channel.shared');

@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
setState(() {
url = "sample";
});
}

@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
getChannel();
}
}

void getChannel() async {
var message = await channel.invokeMethod("getSharedText");
debugPrint(message);
setState(() {
url = message;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text(url),
]
),
);
}
}



I tried to get data in `channel.invokeMethod(&quot;getSharedText&quot;);`, but it returns `null`.

Are there any problem in my code?

</details>


# 答案1
**得分**: 1

尝试在 `result.success(sharedText);` 这行代码的位置返回测试值。如果这样可以的话,就在 `handleSendText` 函数内部添加日志,使用以下代码:
```java
log.d("RequiredVal" + sharedText)

然后在日志中查找这个值。可能 sharedText 为空。

英文:

Try to return testing value at the place of result.success(sharedText);. if its working then add logs inside handleSendText with this code
log.d("RequiredVal" + sharedText).
then find this value in logs. maybe sharedText is null.

huangapple
  • 本文由 发表于 2020年10月20日 10:21:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64437578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定