[問題] 從Activity設service thread的參數

看板AndroidDev作者時間14年前 (2012/02/09 23:43), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串1/2 (看更多)
大家好,我有一個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

02/11 02:18, , 1F
有HandlerThread可以直接用 不需要自己寫
02/11 02:18, 1F

02/11 02:19, , 2F
Handler建立方法則為new Handler(thread.getLooper());
02/11 02:19, 2F

02/11 02:21, , 3F
印象中在ApiDemo裡的某一個Service範例就是這種作法
02/11 02:21, 3F

02/11 22:53, , 4F
回樓上:IntentService
02/11 22:53, 4F
文章代碼(AID): #1FC-clVJ (AndroidDev)
文章代碼(AID): #1FC-clVJ (AndroidDev)