Is notification mandatory while app is running(visible) for the foreground service in API>25

后端 未结 2 666
星月不相逢
星月不相逢 2021-01-28 16:00

From the stackoverflow and many blogs, i surely understand that foreground service never run without notification in API>25. But still i confuse that Is notification mandory whi

2条回答
  •  遥遥无期
    2021-01-28 16:53

    It's not possible to remove the notification while the foreground service is running, but it is possible to change your foreground service back into a "regular" service. This removes the need for a notification. In fact, the function to use,

    stopForeground(boolean removeNotification)

    ...includes a removeNotification parameter just for that purpose. You service can switch from being "foreground" to "regular" on demand, by alternating calls to startForeground() and stopForeground().

    In case it's not clear, you'd probably want to call stopForeground() whenever you have at least one Activity in a "started" state. This is something you'd have to track manually. Then, when the number of "started" activities reaches 0, you'd call startForeground().

    EDIT

    One approach is to use a bound service. Then, it's easy to call stopForeground() on it when you want.

    Assume you have a single Activity. You can bind it to the service (see this doc or use one of these examples). Then your onServiceConnected() function could look like this (adapted from the Google example):

    //MyActivity.java:
    
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mService.stopForeground(true);      //This makes the notification go away
        bound = true;
    }
    
    ...
    
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MyService.class), this, Context.BIND_AUTO_CREATE);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (bound) {
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(text)
                .setAutoCancel(true);
    
            Notification notification = builder.build();
            mService.startForeground(1, notification);    //This brings the notification back! Service is already running, and continues to run.        
    
            unbindService(this);
            bound = false;
        }
    }
    

提交回复
热议问题