Calling a Activity method from BroadcastReceiver in Android
try this code :
your broadcastreceiver class for internet lost class :
public class InternetLostReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}
in your activity add this for calling broadcast:
public class TestActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// internet lost alert dialog method call from here...
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
}
Call activity method from broadcast receiver android?
I was able to solve it by declaring receiver programmatically:
In the activity befor sending the message
private void sendSMS() {
BinarySMSReceiver smsReceiver = null;
smsReceiver = new BinarySMSReceiver();
smsReceiver.setActivityHandler(this);
IntentFilter portIntentFilter = new IntentFilter("android.intent.action.DATA_SMS_RECEIVED");
portIntentFilter.addDataAuthority("*", "9512");
portIntentFilter.addDataScheme("sms");
registerReceiver(smsReceiver, portIntentFilter);
String messageText = etMobile.getText().toString().trim();
short SMS_PORT = 9512;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendDataMessage(etMobile.getText().toString().trim(), null, SMS_PORT, messageText.getBytes(), null, null);
}
In receiver class
public class BinarySMSReceiver extends BroadcastReceiver {
VerifyActivity vAct = null;
void setActivityHandler(VerifyActivity main) {
vAct = main;
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (null != bundle) {
String info = "SMS from ";
String sender = "";
String msg = "";
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
byte[] data = null;
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sender += msgs[i].getOriginatingAddress();
info += msgs[i].getOriginatingAddress() + "\n";
data = msgs[i].getUserData();
for (int index = 0; index < data.length; ++index) {
info += Character.toString((char) data[index]);
msg += Character.toString((char) data[index]);
}
}
Log.e("message", "receiver " + msg);
Log.e("sender", "from " + info);
vAct.msgReceived(msg); //activity method
}
}
}
Unregister the receiver
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(smsReceiver);
}
Call an activity method from a BroadcastReceiver class
Create the BroadcastReceiver dynamically:
In your BroadcastReceiver class define class 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(yourBR, callInterceptorIntentFilter);
finally, when yourBR.onReceive is fired you can call:
yourMain.methodOfMainActivity();
call activity method from broadcast receiver
Thanks @Manishika. To elaborate, making the Broadcastreceiver dynamic, instead of defining it in the manifest, did the trick. So in my broadcast receiver class, i add the code :
MainActivity main = null;
void setMainActivityHandler(MainActivity main){
this.main=main;
}
In the end of the onReceive function of the BroadcastReceiver class, I call the main activity's function :
main.verifyPhoneNumber("hi");
In the main activity, I dynamically define and register the broadcast receiver before sending the sms:
SmsReceiver BR_smsreceiver = null;
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setMainActivityHandler(this);
IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver,fltr_smsreceived);
Calling Main activity method in broadcastReceiver
This is because when your broadcast receiver executes your MainActivity's method, then might be chances that your activity is not running or not even starts, so this kind of problem occurs.
How to solve:
- Create one global class.
- Made your
showNotification
method public static there, if you want then pass the context.
3.just call it from main activity as well in broadcast receiver.
If you are unable to make static method, then just create object of that global class, and call that method using object.
Tell me if you face any problem while implementing this.
Call Activity Method from BroadcastReceiver
Your Activity will likely be long killed and dead by the time the AlarmManager
triggers your BroadcastReceiver
. When that happens, Android will create a new process for your application, instantiate your BroadcastReceiver
and call onReceive()
. This is why the variable viewScheduleActivity
is null
.
As @Athena suggested, you don't need to call back into your Activity in order to cancel alarms.
Calling a activity method from a BroadCast Receiver
Your Context context;
of the MainActivity
is never assigned,
change your code to this
public static void additionDone(int number, Context context){
...//work with that context
}
and in your reciever
MainActivity.additionDone(1, context); //call with the context you got in your receiver constructor
Related Topics
Fast Scroll Display Problem with Listadapter and Sectionindexer
Input Has Different Style on Focus
Cordova Cannot Add Android Failed with Exit Code Enoent
Shared Preferences Reset Data When App Is Force Closed or Device Is Restarted
Obtain Root Access via Su on the Android Emulator
Using Asynctask to Speed Up Android App Launch Time
Android Collapsingtoolbarlayout Collapse Listener
Does Edittext.Gettext() Ever Returns Null
Android - Correct Use of Invalidateoptionsmenu()
Android Browser Ignores Responsive Web Design
How Is an Intent Service Declared in the Android Manifest
Activity.Finish() Called But Activity Stays Loaded in Memory
How to Solve Render Problem Path.Op() Not Supported
Error Inflating Class Android.Support.V4.View.Viewpager