App stops responding when running onStartCommand

Asked

Viewed 60 times

0

I call the service at onPause() And once 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 execute in the background. I need to check the schedule 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;
    }

treatise:

   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 ok loop, but I see another way to do the check

1 answer

1


The Service is not a Thread separate, it means that it rotates in its Main Thread thus making your application stop responding.

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

Would look that way:

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 be executed in a new Thread. The way it’s in your code, it runs on onPause() until the end, why the problem happens.

Don’t forget to also stop the service after finishing the routine execution.


See more in the links below:

Android Service Example

Antipattern: Freezing the UI with a Service and an Intentservice

  • It was right! Thanks again :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.