作者PCIT (岡山的火車  N I
看板AndroidDev
標題[問題] 從Activity設service thread的參數
時間Thu Feb 9 23:43:40 2012
大家好,我有一個IPC的問題想請教有經驗的板友
我有一個Activity,裡面有幾個buttons,用戶可以按其中一個開始service
這個service會啟動一個thread。然後thread的run method 有一個while loop like
while(!Thread.currentThread().isInterrupted())
{
poll data from web
process data
send notification
}
如今,我想要讓用戶可以改變send notification裡面的內容。例如,
讓用戶自行決定message要不要振動。
所以,我想把我thread裡面的while loop用Looper class改寫。然後用message queue
來決定要不要設這些attributes
while(!Thread.currentThread().isInterrupted())
{
Message msg = mq.dequeue()
check_msg(msg);
long poll data from web
process data
send notification
}
不過這個問題就在於,mq.dequeue()是block operation,如果queue是空的,
它會block到有東西為止。不過我的情形是要一直做同一件事(pull data from web),
直到用戶要不同的資料再用message queue來溝通。
所以我想到的解決方法有兩個,不知道哪個比較好?還是都不好XD
1.)在while loop的最後,新增一個sendEmptyMessage(0),所以至少有一個message
在queue裡面。
2.)register message idleHandler。如果queue是空的話,在callback裡
sendEmptyMessage,return true,所以這個handler會一直active。
請問我該用哪種方法好呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 72.201.78.127
推 weruioi:有HandlerThread可以直接用 不需要自己寫 02/11 02:18
→ weruioi:Handler建立方法則為new Handler(thread.getLooper()); 02/11 02:19
→ weruioi:印象中在ApiDemo裡的某一個Service範例就是這種作法 02/11 02:21
推 tomap41017:回樓上:IntentService 02/11 22:53