Reputation: 955
I have a service with a BroadcastReceiver
.
How can I call a function in the service class from the onReceive
function of the BroadcastReceiver
?
And if I can't, what can I do?
Here is some code :
public class MyService extends Service {
private BroadcastReceiver broadcastReceiver;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
... // How to call myFunction() here?
}
};
... // intentFilter, registerReceiver, etc...
}
private void myFunction() {
... // do something
}
}
Upvotes: 1
Views: 1781
Reputation: 7957
You can call it like this:
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
myFunction();
}
};
Or, if myFunction
has the same name as a BroadcastReceiver
method, you can explicitly call the outer class method like this:
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MyService.this.myFunction();
}
};
Upvotes: 1