我有一个广播接收器类,当我接收到特定的广播时,我想停止前台通知。所以我尝试了context.stopForeground(),但是智能感知没有显示该方法。如何调用broadcast receiver类中的stopForeground()方法?
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();
}
}
}发布于 2016-08-03 00:59:27
stopForeground()是Service类的一部分,因此既不能从接收器调用,也不能从提供给它的context调用。
要将现有Service中的BroadcastReceiver设置为实例变量,请执行以下操作:
private final BroadcastReceiver mYReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Bla bla bla
stopForeground(NOTIF_ID);
};您只能在您的Service (可能是在onStartCommand()上)中注册此接收器,方法是:
IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);这将使mYReceiver能够在使用该IntentFilter的广播被触发时触发,您可以在应用程序中的任何位置执行以下操作:
sendBroadcast(new Intent("my.awesome.intent.filter"))发布于 2021-06-16 17:16:17
如果您想在您的接收器中停止广播接收器//
@Override
public void onReceive(Context context, Intent intent) {
context.stopService(new Intent(context, YourService.class);
}同时在相关服务的onDestroy方法中添加stopForground (true)
https://stackoverflow.com/questions/38726398
复制相似问题