Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...