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

Asked

Viewed 58 times

1

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

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

Here’s 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");
    }

}

2 answers

1

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

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
  • It is not very logical to create a new Thread and then execute the code in the original Thread (the one where Handler was created).

1


Edit after question editing.

If what you want is the first notification to be made with a delay the same as the following

 handler.post(runnable);

for

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

Will stay 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 response.

If to run in 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 to run in 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 Handler is preferable, since launching a service is a quick operation.

  • That’s just what I wanted.

Browser other questions tagged

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