Want to hide Notification but getting Context.startForegroundService() did not then call Service.startForeground()

青春壹個敷衍的年華 提交于 2019-12-11 17:15:23

问题


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.



来源:https://stackoverflow.com/questions/53704426/want-to-hide-notification-but-getting-context-startforegroundservice-did-not-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!