我正在从flutter小部件启动android前台服务并在android活动中接收广播。我想将收到的消息返回到flutter页面并根据操作打开页面(我从服务触发广播意图)。我总是收到消息,但有时页面没有被推送。任何帮助都将非常有用。谢谢
Android活动
class MyReceiverTest : BroadcastReceiver() {//registered in manifest
override fun onReceive(p0: Context?, intent: Intent?) {
if (intent!!.action != null) {
when (intent.action) {
"action1" -> {
val extras = intent.extras
if (extras != null) {
if (extras.containsKey("message1")) { var msg = extras.getString("message1")
Handler(Looper.getMainLooper()).post {
channel!!.invokeMethod("action1Method", msg)
}
} }
}
"action2" -> {
val extras = intent.extras
if (extras != null) {
if (extras.containsKey("message2")) { var msg = extras.getString("message2")
Handler(Looper.getMainLooper()).post {
channel!!.invokeMethod("action2Method", msg)
}
} }
}
}
}
}
}
颤振代码
class TestPage extends StatefulWidget {
TestPage({Key key}) : super(key: key) {
methodChannel.setMethodCallHandler(_handleMethodTest);
}
@override
_TestPageState createState() => _TestPageState();
}
Future<dynamic> _handleMethodTest(MethodCall call) async {
switch (call.method) {
case "action1Method":
print("action1");
var actionData1 = call.arguments.toString();
print("Value of action1 " + actionData1);//always printed
ExtendedNavigator.ofRouter<Router>().pushNamed(
Routes.oneRoute);//sometimes doesnot work
break;
case "action2Method":
print("action2");
var actionData2 = call.arguments.toString();
print("Value of action2 " + actionData2);//always printed
ExtendedNavigator.ofRouter<Router>().pushNamed(
Routes.twoRoute);///sometimes doesnot work
break;
}
}
class _TestPageState extends State<BottomNavPage> {
@override
initState() {
super.initState();
//methodChannel.setMethodCallHandler(_handleMethodTest);
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottonNavWidget(),
body: BodyWidget()
);
}