在Android中动态创建BroadcastReceiver
我正在构建一个 Android 应用程序,它通过短信向用户提供信息。用户将短信发送到应用程序中硬编码的预定号码,然后收到响应。
为了实现这一点,我在 Android 清单中使用广播接收器。
<receiver android:name=".SMSReciever">
<intent-filter android:priority="2">
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
如果我创建一个新类 SMSReciever,那么当收到响应时,我会以某种方式将信息发送回用户在屏幕上打开的活动。我是否可以在我的主要活动中动态地执行此操作,以便使应用程序更具交互性?
我已经了解了 Context.registerReciever 方法,但是如何提及接收者的优先级?如果接收者没有更高的优先级,那么消息传递应用程序可能会阻止广播到达我的应用程序。有没有人遇到过类似问题的解决方案?
I am building an Android app that works by providing information via SMS to users.Users send an SMS to a predetermined number hardcoded in the APP and in turn receive a response.
To achieve this, I am using a broadcast Receiver in my Android Manifest
<receiver android:name=".SMSReciever">
<intent-filter android:priority="2">
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
If I create a new class SMSReciever, then when a response is received, I would to somehow send the information back to the activity which the user has open on the screen. Is it possible I can do this in my main activity dynamically so that the app can be made more interactive?
I have learnt about the Context.registerReciever method, but how do I mention the priority for the receiver? If the receiver does not have a higher priority, then the messaging app might stop the broadcast from reaching my app. Has anyone come across a solution for something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用以下代码来实现我想要的!
I used the following code to achieve what I was looking for!
我自己没有测试过,但我通过 Android 源代码进行了快速搜索。
优先级被解析并保存到
IntentFilter
中(请参阅 代码)。因此,您可以创建IntentFilter
并使用其setPriority()
函数设置广播接收器的优先级。I haven't tested this myself, but I've made a quick search via Android source code.
The priority is parsed and saved into
IntentFilter
(see code). So you can createIntentFilter
and use itssetPriority()
function to set priority of your broadcast receiver.我将通过使用诸如 com.example.intent.VERIFICATION_RECEIVED 之类的自定义意图操作来解决此问题,并从
SMSReciever
广播此操作,然后让您的Activity
使用BroadcastReceiver
监听它。使用这种方法,您可以将 SMS 处理保留在
SMSReciever
中,并且您的Activity
不需要关心如何处理 SMS。I would solve this by using a custom intent action like
com.example.intent.VERIFICATION_RECEIVED
and the broadcasting this fromSMSReciever
and then having yourActivity
listen for it with aBroadcastReceiver
.Using this approach you can keep your SMS handling in
SMSReciever
and yourActivity
doesn't need to care about how to handle a SMS.