Android调用startForeground 但不显示通知

本文介绍了如何在Android中使用startForeground提升Service优先级,同时避免在通知栏显示通知。通过结合ForegroundService和引导Service(ForegroundEnablingService),在指定相同NOTIFICATION_ID后关闭引导Service,可以在Android 7.1以下版本实现隐藏通知的效果。
摘要由CSDN通过智能技术生成

有时候我们想使用startForeground提升Service的进程优先级,但是startForeground会在手机通知栏显示通知。为了去除通知,可以借助目标Service(ForegroundService )和引导Service(ForegroundEnablingService),使用以下trick(不支持 Android 7.1):

  1. 正常启动ForegroundService ,调用startForeground并指明NOTIFICATION_ID 。

  2. 启动ForegroundEnablingService,调用startForeground并指明相同NOTIFICATION_ID
    ,再关闭该Service,即可隐藏通知。

代码如下:

ForegroundService.java

public class ForegroundService extends Service {

    static ForegroundService instance;

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        if (startService(new Intent(this, ForegroundEnablingService.class)) == null)
            throw new RuntimeException("Couldn't find " + ForegroundEnablingService.class.getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        instance = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

ForegroundEnablingService.java

public class ForegroundEnablingService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (ForegroundService.instance == null)
            throw new RuntimeException(ForegroundService.class.getSimpleName() + " not running");

        //Set both services to foreground using the same notification id, resulting in just one notification
        startForeground(ForegroundService.instance);
        startForeground(this);

        //Cancel this service's notification, resulting in zero notifications
        stopForeground(true);

        //Stop this service so we don't waste RAM.
        //Must only be called *after* doing the work or the notification won't be hidden.
        stopSelf();

        return START_NOT_STICKY;
    }

    private static final int NOTIFICATION_ID = 10;

    private static void startForeground(Service service) {
        Notification notification = new Notification.Builder(service).getNotification();
        service.startForeground(NOTIFICATION_ID, notification);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

AndroidManifest.xml

<service android:name=".ForegroundEnablingService" />
<service android:name=".ForegroundService" />

http://stackoverflow.com/questions/10962418/how-to-startforeground-without-showing-notification

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值