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); 
相關問題