Here I am creating an online application that depends only on Internet.
So whenever there is a network error it must notify user. For that, I have created a BroadcastReciver that receives call when network connection gets lost(Internet).
All this works perfectly. Now what I need is that I have to call a method of Activity from this Broadcast Receiver, where I have created an Alert Dialogue.
I have read many answers on stack-overflow.com that I can declare that method static and call by using only Activity name,
e.g MyActivityName.myMethod()
But I can't declare my method static, because I am using Alert Dialogue there and it shows me error on line,
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
that Cannot use this in a static context.
So, how can I call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?
And can I get Activity(or fragment) name from Broadcast Receiver which is currently running?
Add a boolean variable in you activity from where you are open alertdialog
And replace your code for alertdialog with this one
Pass your Activity's context to BroadcastReceiver's contructor.
and in your MainActivity
hope it helps
try this code :
your broadcastreceiver class for internet lost class :
in your activity add this for calling broadcast: