作者iincho (世界的尽头)
看板AndroidDev
标题Re: [问题] 从Activity设service thread的参数
时间Fri Feb 10 00:23:00 2012
※ 引述《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
1F:推 PCIT:我的service一开始跟activity同一个process, 02/10 02:42
2F:→ PCIT:为了避免read()block UI thread, 才开另一个thread 02/10 02:43
3F:→ PCIT:我也有想到用sharedPrefernce,可是我不确定 02/10 02:43
4F:→ PCIT:它是不是thread safe, 才想用message queue 02/10 02:44
5F:→ iincho:不是thread safe可以自己卡.... 02/10 14:11
6F:→ iincho:或者你可以用Broadcast Reciever..:p 02/10 17:57