Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

android - Using Handler inside service

Can i use this code inside a service for calling a method with delay or Handler() should only be used inside a UI thread ?

What is the best way for calling a method with delay inside a service?

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 10000ms
    socket.emit("CancelTravel");
  }
}, 10000);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Handler() only should be use inside a UI thread ?

Yes Handler() usefull only on UI thread and if you want use on normal thread, you need to implement looper

Sample code

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 10000ms
            socket.emit("CancelTravel");

        }
    }, 5000);

You can also use Timer

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

Sample Code

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        //Do something after 10000ms
    socket.emit("CancelTravel");       
    }
}, 10000);

what is preferred way for calling a method with delay inside a service?

Read Timertask or Handler


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...