WeirdNerd WeirdNerd - 4 months ago 23
Android Question

Why can't we call StopForeground() method in the broadcast receiver class?

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();

}


}
}

Answer

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);
    };
Comments