简体   繁体   English

如何在不重新启动的情况下将广播接收器的信息发送回我的主要活动

[英]how can i send information from broadcast receiver back to my main activity without restarting it

  if (messages.length > -1) {
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(context, "Message recieved: " + messages[0].getOriginatingAddress(), duration);
                        toast.show();
                        String value = "Message recieved: " + messages[0].getOriginatingAddress();

my code here gets an sms. 我的代码在这里得到一个短信。 i want to bring it back to my main activity but i CANT use i intent and restart that activity(the broadcast reciever is a background service and people will be using the app during this.) instead of toasting how can i pass that string back to the activity (i only have one main one). 我想把它带回我的主要活动,但我不能使用我的意图并重新启动该活动(广播接收器是后台服务,人们将在此期间使用该应用程序。)而不是敬酒我怎样才能将该字符串传递给活动(我只有一个主要活动)。

If you want to have your activity notified only when is in foreground, just throw a new broadcast from the sms broadcast receiver and intercept it from a broadcast receiver hosted in your activity. 如果您希望仅在前台通知您的活动时,只需从短信广播接收器发送新广播,并从您活动中托管的广播接收器中截取它。

On the other hand, if you want to check if the broadcast was sent when the activity comes back to foreground, even if the sms was received while the activity was in background, you can still use a broadcast receiver but you need to add a sticky intent which can be received afterwards. 另一方面,如果你想检查当活动回到前台时是否发送了广播,即使在活动处于后台时收到了短信,你仍然可以使用广播接收器,但你需要添加粘性之后可以收到的意图

Plus: use a local broadcast receiver in order to save resources. 另外:使用本地广播接收器以节省资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM