11

我已为我的应用程序安排了警报。Android - 如何触发广播接收器调用其onReceive()方法?

我已经实现了广播接收器,一旦闹钟时间到达就会被触发。

如何手动调用广播接收器执行onReceive方法内部的代码,而无需复制代码两次。

我想在实用单例调用中使用代码,并通过在任何地方使用util类实例来调用该方法。

但是,是否有任何其他方式直接调用onReceive方法或其他问题广播意图。

android:exported =“false”//在清单文件中定义 时,接收者的附加参数。

另一个问题是导出的参数是什么意思。请帮我理解这一点。

回答

20

手动启动BroadcastReceiver的方法是调用

Intent intent = new Intent("com.myapp.mycustomaction"); 
sendBroadcast(intent); 

其中"com.myapp.mycustomaction"是在清单您BroadcastReceiver指定的操作。这可以从ActivityService调用。

2.据了解,Android允许应用程序使用其他应用程序的组件。这样,我的应用程序的Activity s,Service s,BroadcastReceiver s和ContentProvider可以由外部应用程序启动,只要在清单中设置属性android:exported = true即可。如果它设置为android:exported = false,则该组件不能由外部应用程序启动。见here

+0

u能请张贴整个代码... – 2015-02-23 10:01:21

+0

您可以添加意图过滤器定义吗?到目前为止,OP可能已经明确地调用它 – 2015-02-23 10:07:55

+0

感谢Zygotelnit。是的,我可以打电话给它。 – 2015-02-23 10:09:01

2

如何手动调用广播接收器执行onReceive方法中的代码,而无需复制代码两次。

Intent intent=new Intent(CUSTOM_ACTION_STRING); 
// Add data in Intent using intent.putExtra if any required to pass 
sendBroadcast(intent); 

什么是机器人:出口参数意味着

正如android:exported DOC:

使用这 AndroidManifest.xml添加 sendBroadcast同样的动作

消防BroadcastReceiver无论是否广播接收机可以接收来自应用程序之外来源的消息 - 如果可以,则为“真”,而“假”则为i因此若没有

意味着,如果:

机器人:出口=真:其他应用程序也能使用行动

机器人射击这个广播接收器:出口=假:其他应用程序不能使用动作触发此广播接收器

+0

并从命令'adb shell am broadcast -a ACTION_STRING'。 – 2015-02-23 10:06:35

6

您需要提及需要由Android OS进行过滤以通知您的action。 即: 清单文件中,

<receiver 
android:name="com.example.MyReceiver" 
android:enabled="true" > 
<intent-filter> 
    <action android:name="com.example.alarm.notifier" />//this should be unique string as action 
</intent-filter> 

每当你想打电话给广播接收机的onReceive方法

Intent intent = new Intent(); 
intent.setAction("com.example.alarm.notifier"); 
sendBroadcast(intent);