Service stops working when app gets closed

前端 未结 2 2002
孤城傲影
孤城傲影 2020-12-07 04:26

Here I have implemented functionality to read messages of incoming push notifications using Text-To-Speech. I created a separate service class for it which works fine and a

相关标签:
2条回答
  • 2020-12-07 04:37

    From the API level 26, android restricted background service access. You can solve this by starting your service as a foreground.

    I had the same issue with my one project and i have fixed it by using below code.

    In YourService.class

    private static final String NOTIFICATION_CHANNEL_ID_DEFAULT = "my_flow_notification_channel_default";
    
    @Override
        public void onCreate() {
            super.onCreate();
    
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_DEFAULT)
                    .setOngoing(false).setSmallIcon(R.drawable.ic_notification).setPriority(Notification.PRIORITY_MIN);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_DEFAULT,
                        NOTIFICATION_CHANNEL_ID_DEFAULT, NotificationManager.IMPORTANCE_LOW);
                notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID_DEFAULT);
                notificationChannel.setSound(null, null);
                notificationManager.createNotificationChannel(notificationChannel);
                startForeground(1, builder.build());
            }
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO: 
         return START_STICKY;
        }
    

    To Start Service

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
         ContextCompat.startForegroundService(context, new Intent(context, YourService.class));
    else
         context.startService(new Intent(context, YourService.class));
    

    To Stop Service

    stopService(new Intent(getActivity(), YourService.class));
    

    In Your AndroidManifest.xml

    Add this permission

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    

    Add this inside Tag.

    <service
       android:name=".service.YourService"
       android:enabled="true"
       android:exported="true" />
    

    Hope this help.. :)

    0 讨论(0)
  • 2020-12-07 04:53

    You better to use IntentService for background services if service is not in Opened. Follow this document IntentService , Keep Coding :)

    0 讨论(0)
提交回复
热议问题