Calling main activity from BroadcastReceiver
While developing an alarm based application, i have stuck in a scenario.
When my alarm is fired, i can receive the event in BroadCastReceiver::onReceive().开发者_JS百科 Within this function, i want to notify/call a function, which is located on MainActivity.
How to achieve the same??
Can't you just move the function to it's own class and call it from both your Activity AND your Receiver?
Create the BroadcastReceiver dinamically:
in your BroadcastReceiver class define member:
YourMainActivity yourMain = null;
and method:
setMainActivityHandler(YourMainActivity main){
yourMain = main;
}
from your MainActivity do:
private YourBroadcastReceiverClassName yourBR = null;
yourBR = new YourBroadcastReceiverClassName();
yourBR.setMainActivityHandler(this);
IntentFilter callInterceptorIntentFilter = new IntentFilter("android.intent.action.ANY_ACTION");
registerReceiver(callInterceptor, callInterceptorIntentFilter);
finally, when yourBR.onReceive is fired you can call:
yourMain.methodOfMainActivity();
精彩评论