问题
I have a broadcast receiver class and when I receive a particular broadcast I would like to stop the foreground notification. So I tried context.stopForeground() but the intellisense did not show the method. How can we call the stopForeground() method in the broadcast receiver class ?
public class Broad extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()==Const.ACTION_STOP)
{
// unable to call like this
context.stopForeground();
}
}
}
回答1:
stopForeground() is part of the Service class and therefore it cannot be called from either the receiver or the context provided to it.
To setup a BroadcastReceiver in your existing Service as an instance variable:
private final BroadcastReceiver mYReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Bla bla bla
stopForeground(NOTIF_ID);
};
You register this receiver in your Service only (possibly on onStartCommand()), using:
IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);
This will enable mYReceiver to be triggered whenever a broadcast with that IntentFilter is fired which you can do from anywhere in your app as:
sendBroadcast(new Intent("my.awesome.intent.filter"))
来源:https://stackoverflow.com/questions/38726398/why-cant-we-call-stopforeground-method-in-the-broadcast-receiver-class