Android - 如何触发广播接收器调用其onReceive()方法?

M V*_*esh 17 android broadcastreceiver android-manifest android-intent android-broadcast

我为我的申请安排了警报.

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

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

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

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

android:exported ="false"//在清单文件中定义时接收者的附加参数.

另一个问题是导出的参数意味着什么.请帮我理解这个.

Y.S*_*Y.S 26

1.BroadcastReceiver手动启动的方法是通过调用

Intent intent = new Intent("com.myapp.mycustomaction");
sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

清单中"com.myapp.mycustomaction"为您指定的操作在哪里BroadcastReceiver.这可以从a Activity或a 调用Service.

2.众所周知,Android允许应用程序使用其他应用程序的组件.这样,只要在清单中设置了属性,我的应用程序的Activitys,Services,BroadcastReceivers和ContentProviders就可以由外部应用程序启动android:exported = true.如果设置为android:exported = false,则外部应用程序无法启动此组件.看到这里.


Eri*_*ric 8

这是一个更类型安全的解决方案:


Meh*_*sar 7

您需要提及actionAndroid操作系统需要过滤哪些内容才能通知您.即:内部清单文件,

<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>
Run Code Online (Sandbox Code Playgroud)

无论何时你想调用广播接收者的onReceive方法,

Intent intent = new Intent();
intent.setAction("com.example.alarm.notifier");
sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)