0

I have one service on my Android App, this service posts in my server every 20 seconds when the session of user in my App is active.

This runs ok during several days if my device is connected to power, but if the device is disconnected and is unused (with the screen off) the service seems to stop but few minutes later begin to run again and continues to run for hours.

In the service, I use wakelock to avoid the device from going to sleep mode.

I apologize for my English so basic

Pablo Crucitta
  • 374
  • 2
  • 7

2 Answers2

1

The problem was that I was testing on a device with Android version 6 and for this we must use setAlarmClock to wake the device.

        Intent intent = new Intent(context, MyWakefulBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        long triggerAtMillis = System.currentTimeMillis() + 20 * 1000;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(triggerAtMillis, pendingIntent);
            alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        } else {
            alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        }
Pablo Crucitta
  • 374
  • 2
  • 7
0

Because your service is killed when your activity is killed. if you want that your service still running dont' use Context.bindService() to start it but Context.startService(). for more details check this link How to start your service and to know all about services http://developer.android.com/reference/android/app/Service.html

Community
  • 1
  • 1
user2043602
  • 237
  • 2
  • 4
  • 15