0

I am creating an application which will check status of the villages in one game and i have a problem.

I have background service which have set time 60s and it's repeat. Everything looks fine but after some time (10-30 minutes) when i give application on background timer delayed.

for example: 1. execute - 10:55:00 2. execute - 10:57:10 3. execute - 10:58:30 4. execute - 10:59:50 5. execute - 11:01:30 6. execute - 11:03:00

This is screen of times log in application: Application Image

This occurs only when i minimize the application to background. When i am in application, everything is fine.


Actual Service

private ArrayList<Village> villages=null;
private boolean isNotificationEnable=true;
private boolean result;

public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;

Thread thread;
private volatile boolean running = true;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    runnable = new Runnable() {
        public void run() {
            while(true) {
                if (!running) return;
                if (updateVillages()) {
                result = true;
                if (isNewVillage()) {
                    if (isNotificationEnable) doNotificate();
                }
                System.out.println("Prebehlo overovanie");
            } else {
                result=false;
                System.out.println("Není internetové pripojenie");
            }
            updateUI();

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    thread= new Thread(runnable);
    thread.start();

}



@Override
public void onDestroy() {
    /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
    //handler.removeCallbacks(runnable);
    Toast.makeText(this, "Kontrolovanie dedín bolo vypnuté", Toast.LENGTH_LONG).show();
    running=false;
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Kontrolovanie dedín bolo zapnuté", Toast.LENGTH_LONG).show();
}




//MyCode

Actual code. The delay started when mobile is disconnect from charger. When is mobile on charger everything work fine and updating 60s. Some help to fix this?

EDIT 6.4.2018 My service now.

ublic class BackgroundService extends Service {

private ArrayList<Village> villages=null;
private boolean isNotificationEnable=true;
private boolean result;

public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;

Thread thread;
private volatile boolean running = true;

private Notification notification;
private MediaPlayer player;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
    wakelock.acquire();

    /*Intent intent = new Intent(this, Menu.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent,   PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setSmallIcon(R.drawable.ic_warning_black_24dp);
    builder.setTicker("App info string");
    builder.setContentIntent(pi);
    builder.setOngoing(true);
    builder.setOnlyAlertOnce(true);

    notification = builder.build();*/

// optionally set a custom view

    //startForeground(2, notification);

    /*player = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI);
    player.setLooping(true);
    player.start();*/
    //handler=new Handler();

    runnable = new Runnable() {
        public void run() {
            while(true) {
                if (!running) return;
                if (updateVillages()) {
                result = true;
                if (isNewVillage()) {
                    if (isNotificationEnable) doNotificate();
                }
                System.out.println("Prebehlo overovanie");
            } else {
                result=false;
                System.out.println("Není internetové pripojenie");
            }
            updateUI();

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    //handler.postDelayed(runnable, 60000);

    thread= new Thread(runnable);
    thread.start();
}


@Override
public void onDestroy() {
    /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
    //handler.removeCallbacks(runnable);
    Toast.makeText(this, "Kontrolovanie dedín bolo vypnuté", Toast.LENGTH_LONG).show();
    running=false;
    //player.stop();
    //stopForeground();
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Kontrolovanie dedín bolo zapnuté", Toast.LENGTH_LONG).show();
    //startForeground(2, notification);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO do something useful

    return START_STICKY;
}

EDIT/// My AlertManager but work only for 1 min interval.

 public void startAlert() {
    int timeInSec = 2;

    Intent intent = new Intent(this, BackgroundService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 50000,
            intent, 0);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + 1000, 5000, pendingIntent);
}
  • its seem your calling your service twice and is your service running in background also when app get killed? – Nikhil Sharma Apr 05 '18 at 08:44
  • Yes, the call still run when application is dead (it's not fixed now) but my application is still runing. It 's only minimized in the background. – Erik Juríček Apr 05 '18 at 08:47
  • its mean your service gets restarted when you close application, can you share full code from where you calling service and manifest – Nikhil Sharma Apr 05 '18 at 08:49
  • In first time i try do it with AsynchTask and i used Thred.sleep(xxxx) but i have the same problem. When i have application on foreground everything was ok, process do every 60 second, but when i give application on background then timer was 70,80,90 second, after some time 4-15 minutes. – Erik Juríček Apr 05 '18 at 08:50
  • your activity code seems ok but i suggest you to write own thread inside service, inside run put while(true) and sleep – Nikhil Sharma Apr 05 '18 at 09:00
  • a try do this with sleep in asynch task but i have the same result. First few minutes it was everything ok but some time i have massive delay. – Erik Juríček Apr 05 '18 at 09:03
  • i mean without aynctask just writeup for thread only or else you can use AlarmManager – Nikhil Sharma Apr 05 '18 at 09:05
  • I go try the Thread then they will see – Erik Juríček Apr 05 '18 at 09:11
  • I add the Thread and i go testing it. first 10 minutes see good, but i need test it few hours. – Erik Juríček Apr 05 '18 at 09:33
  • I tested it for an hour on the charger and everything worked super, updating around every 60s. After I disconnected the charger, it started to be a massive delay. Now I think it's caused by a charger, and when I take it off I will start a delay. Some help how fix this? – Erik Juríček Apr 05 '18 at 10:40
  • Then it might me your phone setting , you have turn on your power saving mode , which doesnt work on charging..check once and let me know what happn – Nikhil Sharma Apr 05 '18 at 13:27
  • @Nikhil Sharma It not about phone, i test it on 3 difficulty mobile phones and do it on each other. Now i trie lots of option to do service unstopable but nothing work. I try wakelock, foregraound service but nothing work. If mobile phone is disconnect from charger service begun stop or pause. – Erik Juríček Apr 06 '18 at 06:16
  • So better you use alarm manager . – Nikhil Sharma Apr 06 '18 at 06:39
  • I try it, but it dont work very fine. Better solution for me is service but i need do it unstopable (not pause, not stop, not kill). A use google yesterday and i try use wakelock but it's dont work. I dont know why. A addded him to manifest and i add code to service and nothing. – Erik Juríček Apr 06 '18 at 06:45
  • @Nikhil Sharm Problem is that service not stop but only delayel. The tasks are do but in delayled time. sometimes is service do 1/10 minutes, 1/20 minutes, 1/4 minutes. It's very random. – Erik Juríček Apr 06 '18 at 06:52
  • Yeah even i have tried to make demo application same thing happing with me.. – Nikhil Sharma Apr 06 '18 at 06:53
  • @Nikhil Sharm I read lots of topic where guys have same problem and i don't find some solution. – Erik Juríček Apr 06 '18 at 07:00
  • @Nikhil Sharm I tried use AlarmManager but they do task only every 60s. When i give time like 2s, 5s it's dont work. I edit my actual code. – Erik Juríček Apr 06 '18 at 07:27
  • Erik can you ping me on my id with your code so that i can help you out , if you dont mind sharing your code, my email is "nikhoney27@gmail.com" – Nikhil Sharma Apr 06 '18 at 11:09

0 Answers0