How do I make an operation take moments after I clicked a button?

1

I created a simple android app that starts a service just when I click on a button that I put myself, just click the button it starts to service immediately.

What I want now is that clicking the service button takes some time to start. how can I do this ??

Here is the code that launches the service:

public class NotifyService extends Service {

    private HandlerThread handlerThread;
    private Handler handler;
    private boolean started = false;

    //Define o tempo entre notificações, altere como quiser
    private final int TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS = 7;

    @Override
    public void onCreate() {
        Log.d("NotifyService", "onCreate");

        handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("NotifyService","onStart");

        if(!started) {
            Log.d("NotifyService","Notificações iniciadas");
            started = true;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    sendNotification();
                    handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
                }
            };
            handler.post(runnable);
        }
        return Service.START_NOT_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("NotifyService","Notificações terminadas");
        handlerThread.quit();
    }

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

    private void sendNotification(){
        Intent intent = new Intent (this ,
               Bca.class);
        PendingIntent pendingIntent = PendingIntent.getActivity
                (this, 0, intent, 0);
        Notification notification = new Notification.Builder (this)
                .setContentTitle("Qsmobile")
                .setContentText("Consulte a sua fila")

                .setSmallIcon(R.drawable.bcno)
                .setContentIntent(pendingIntent)
                .getNotification();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager =
                (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
        notificationManager.notify (0, notification);
        Log.d("NotifyService", "notificação enviada");
    }

}
    
asked by anonymous 27.06.2017 / 20:41

2 answers

1

Edit after editing the question.

If you want the first notification to be made with a delay equal to the following

 handler.post(runnable);

by

handler.postDelayed(runnable, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);

It will look like this:

if(!started) {
    Log.d("NotifyService","Notificações iniciadas");
    started = true;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            sendNotification();
            handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
        }
    };
    handler.postDelayed(runnable, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
}

Original answer.

If it is to run on the same Thread

  • use a Handler:

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
    
        @Override
        public void run() {
            lancarServico();
        }
    }, 5 * 1000); // O método é lançado após 5 segundos.
    

If it is to run on another Thread

  • use a HandlerThread:

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    
    handler.postDelayed(new Runnable() {
    
        @Override
        public void run() {
            lancarServico();
        }
    }, 5 * 1000); // O método é lançado após 5 segundos.
    
  • or use Timer and TimerTask

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        public void run() {
           lancarServico();
        }
    };
    timer.schedule(timerTask, 5 * 1000); // O método é lançado após 5 segundos.
    

Creating a new Thread has costs, in this case the use of the Handler is preferable, since launching a service is a quick operation.

    
27.06.2017 / 21:56
1

You need to put it inside a Run, setting the timeout.

For example:

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {       
                    //Inicia aqui o service depois de 5 segundos
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 5000 ms
    
27.06.2017 / 20:49