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

看板AndroidDev作者 (世界的盡頭)時間14年前 (2012/02/10 00:23), 編輯推噓1(105)
留言6則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《PCIT (岡山的火車￾  N￾ I》之銘言: : 大家好,我有一個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。 : 請問我該用哪種方法好呢? 這個做法真是詭異,你如果只要改呈現方式何不開一個 SharedPreference每次送之前去檢查? 不然Activity端搞content provider給service讀看看, 好像沒看過開Thread來做的.... -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.193.107

02/10 02:42, , 1F
我的service一開始跟activity同一個process,
02/10 02:42, 1F

02/10 02:43, , 2F
為了避免read()block UI thread, 才開另一個thread
02/10 02:43, 2F

02/10 02:43, , 3F
我也有想到用sharedPrefernce,可是我不確定
02/10 02:43, 3F

02/10 02:44, , 4F
它是不是thread safe, 才想用message queue
02/10 02:44, 4F

02/10 14:11, , 5F
不是thread safe可以自己卡....
02/10 14:11, 5F

02/10 17:57, , 6F
或者你可以用Broadcast Reciever..:p
02/10 17:57, 6F
文章代碼(AID): #1FC_Bc7j (AndroidDev)
文章代碼(AID): #1FC_Bc7j (AndroidDev)