Background service is not working in Oreo

前端 未结 3 700
后悔当初
后悔当初 2020-12-01 11:43

I want to run my app in background if I kill the app instance also. But after I kill my app the service also stops working. Here is my code please any one help me to solve m

3条回答
  •  攒了一身酷
    2020-12-01 12:22

    You need to create ForegroundService in order continue processing when your app is killed, as follows:

     public class SensorService extends Service{
    
        private PowerManager.WakeLock wakeLock;
        @Override
        public void onCreate() {
            super.onCreate();
    
            //wake lock is need to keep timer alive when device goes to sleep mode          
            final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PARTIAL_WAKE_LOCK_TAG");
            createNotificationChannel(this);
            Notification notification = new NotificationCompat.Builder(this, "NOTIFICATION_CHANNEL").setSmallIcon
                    ().setContentTitle("Title")
                    .setContentText("Content").build();
    
            startForeground(1001, notification);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
    
        }
    
         public void createNotificationChannel() {
            // Create the NotificationChannel, but only on API 26+ because
            // the NotificationChannel class is new and not in the support library
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
                CharSequence name = "Channel name";
                String description = "Description";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel("NOTIFICATION_CHANNEL", name, importance);
                channel.setDescription(description);
                NotificationManager notificationManager = getApplicationContext().getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    

    To start the service:

    Intent i = new Intent(context, SensorService.class);
    ContextCompat.startForegroundService(context, i)
    

    Note:

    • You cannot run service endlessly with this approach. During doze mode if OS recognizes it as CPU intensive then your Service will be terminated.
    • You need to call stopSelf() when your Timer task has been executed successfully.

提交回复
热议问题