在Flutter应用程序中创建广播接收器,并在Flutter应用程序启动时注册它。当从Android原生应用程序发送意图时,Flutter应用程序将在前台,因此,将执行接收器并自动处理意图。
示例代码:
Flutter应用程序中的广播接收器:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
static const MethodChannel _channel =
const MethodChannel('com.example/share_intent');
static Future startReceiver() async {
_channel.setMethodCallHandler((MethodCall call) async {
if (call.method == 'onReceive') {
String text = call.arguments;
// Do something with the received text
}
});
}
}
class _MyAppState extends State {
@override
void initState() {
super.initState();
MyApp.startReceiver();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Share Intent Receiver'),
),
body: Center(
child: const Text('Waiting for text...'),
),
),
);
}
}
在Android Manifest中添加intent-filter:
在MainActivity中发送共享意图:
private void shareText(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
String packageName = "com.example.flutter_app";
String className = "com.example.flutter_app.MainActivity";
intent.setClassName(packageName, className);
startActivity(intent);
}
在Flutter应用