Android Service stops working, when app isn't on the foreground

前端 未结 1 1580
太阳男子
太阳男子 2021-01-25 13:39

I\'ve got a little problem: I recieve from a Service a speed value given by the LocationListener. But when i close the ui of my app then the locationlistener stops sending upd

相关标签:
1条回答
  • 2021-01-25 13:59

    From oreo there's major changes in android background policy, please refer this https://developer.android.com/about/versions/oreo/background for more details, in order to avoid your service from getting killed by android you have to run it as a foreground service

    Step 1: Add permission to manifest file

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

    heres more details on this permission https://developer.android.com/reference/android/Manifest.permission#FOREGROUND_SERVICE

    Step 2: Create service, I'm sharing example code for you

    public class DemoService extends Service {
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d("SSB Log", "onStartCommand");
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // For foreground service
                Intent notificationIntent = new Intent(this, DemoService.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    
                // Creating channel for notification
                String id = DemoService.class.getSimpleName();
                String name = DemoService.class.getSimpleName();
                NotificationChannel notificationChannel = new NotificationChannel(id,
                        name, NotificationManager.IMPORTANCE_NONE);
                NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                service.createNotificationChannel(notificationChannel);
    
                // Foreground notification
                Notification notification = new Notification.Builder(this, id)
                        .setContentTitle(getText(R.string.app_name))
                        .setContentText("Show service running reason to user")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(pendingIntent)
                        .setTicker("Ticker text")
                        .build();
    
                startForeground(9, notification);
            }
            // Service logic here
    
            return Service.START_NOT_STICKY;
        }
    }
    

    Step 3: Declare service in manifest

    <service android:name=".DemoService" />
    

    Step 4: Start service from activity

    Intent startDemoService = new Intent(this,DemoService.class);
        startService(startDemoService);
    
    0 讨论(0)
提交回复
热议问题