Fork me on GitHub

6/28/2011

[Android] 執行週期性任務 - execute period task

最近專案需要定期從系統擷取一些資料,除了開一個 thread 之外,找的一個更為輕量的解決方案,整理如下:

final Handler handler= new Handler();
        
final int delay = 5000; // 5 second
final int period = 1000; // 1 second

final Runnable r = new Runnable() {
    public void run() {
        Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
        handler.postDelayed(this, period);
        }
    };

handler.postDelayed(r, delay);

poseDelayed(): adds the runnable to the queue and it runs in the UI thread

除了這個方法之外還有一些其他的方法:
1. Handlers, and PostDelayed can be nice lightweight ways of having your foreground activity called on a regular basis. Even the messages are reused. These are used in the Snake example program (Snake/SnakeView.java/sleep()) to make the snake move. It runs as 'post a message delayed by 500ms', in 500ms catch it in HandleMessage (the default for Handlers), move, then send it again. Even the message is reused with obtainMessage(). I've used these for making a button update while it is pushed down.

2. Threads are a bit heavier. You might use these for background or where you are already used to running a thread. Make a 'new Thread(aRunnable).start()'. I haven't used them much on the Android.

3. Launch an Intent with StartActivityForResult() and catch the result with OnActivityResult to make a standard RPC. See step 2 of the notepad example for more information.

4. Look into more Intents to launch for different scenarios. I find putting your 'create and launch intent' into separate functions helps maintenance and debugging.

via Android - Question on postDelayed and Threads

參考資料:
  1. 「有人建議不要使用 TimerTasks」: Schedule task in android - Stack Overflow
  2. How to run a Runnable thread in Android? - Stack Overflow

... ...

No comments:

Post a Comment