Want to hide Notification but getting Context.star

2019-08-26 07:27发布

问题:

I want to hide notification from appearing when the service is running in the background. I am aware that as per Google Play rules we have to show notification but for my current app i dont want to display any notification.

Here is the code, which works fine and shows notification. But how to make it not show any notification:

try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = "com.app..";
                String channelName = "App Background Service";
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                channel.setLightColor(Color.BLUE);
                channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(channel);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
                Notification notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("App is running in background")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                startForeground(0, notification);
            } else
            {
                startForeground(0, new Notification());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

If i dont put the above code it gives error saying no startForeground found. And gets killed after 5 sec automatically.

Reason: Context.startForegroundService() did not then call Service.startForeground()

I want the service not show any notification to user and finish its task silently without getting killed. Is that even possible in Build Version > 26?

回答1:

I want the service not show any notification to user and finish its task silently without getting killed

Use JobIntentService and ensure that your work will get done in less than 10 minutes. Note that there may be some delay before the work begins (which will not count against that 10-minute limit).

Or, use IntentService and ensure that your work will get done in less than 1 minute.

Neither of those requires a foreground service.