App stops responding when you run onStartCommand

0

I call service on onPause() of my activity and as soon as I leave the app, it stops responding after a while. From what I've researched it may be that the processes are too heavy to run in the background. I need to check the time to see if it's time to send the notification.

public int onStartCommand(Intent intent, int flags, int startId) {
        if (inicio != null) {
            ok = trataData(d2,d3);
            horaNotificacao.set(Calendar.MILLISECOND,this.intervalo);
            while (ok == true){
                try {
                    agora = new Date();
                    if(agora.equals(horaNotificacao.getTime())){
                        gerarNotificacao();
                        horaNotificacao.set(Calendar.MILLISECOND,this.intervalo);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                ok = trataData(d2,d3);
            }
        }
        return START_STICKY;
    }

treatData:

   public boolean trataData(Date d2, Date d3) {
        boolean ok = false;
        Date d1 = new Date();
        if (d1.before(d2) && d1.after(d3)){
            ok = true;
        }
        return ok;
    }

I think the problem is in this loop of ok, but I see no other way to do the verification

    
asked by anonymous 26.06.2016 / 02:57

1 answer

1

Service is not a separate Thread , it means that it runs on your Main Thread thus causing your application to stop responding.

To solve the problem you need to run your routine inside a new Thread .

It would look like this:

public int onStartCommand(Intent intent, int flags, int startId) {
    new Thread(new Runnable() {
       @Override
       public void run() {
          // Coloque sua rotina aqui dentro
       }).start();
    return Service.START_STICKY;
}

With this, your time-consuming routine will run in a new Thread . As it is in your code, it runs in onPause() until it is finished, so the problem happens.

Do not forget to stop the service after finishing the routine.

See more links below:

Android Service Example

Antipattern: freezing the UI with a Service and an IntentService

    
26.06.2016 / 13:50