[問題] ListView 程式關閉 thread 還是跑

看板AndroidDev作者 (skill)時間13年前 (2013/03/05 16:28), 編輯推噓6(6023)
留言29則, 10人參與, 最新討論串1/1
想請教各位大大 我的app主要在實作 由 listView 從網路上拿資料 拿資料必須要經由 "thread" 從事網路存取 可是如果thread 並沒拿到資料 我此時立刻將app關閉了 再重複開啟 此時 thread 一樣會跑... (就是會存在兩個thread,造成資料拿兩遍) ListView 就會重複出現相同的 entry view 請問要怎樣解決這樣的問題QQ ps. 應該不需要附加程式碼吧? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.163.3.187

03/05 18:42, , 1F
最近也有遇到,似乎邏輯設定要好,thread讓他自動結束
03/05 18:42, 1F
是類似這樣嗎? 宣告 static boolean threadOn = false; if( not threadOn){ threadOn = true thread run } thread running is end => threadOn = false;

03/05 18:44, , 2F
你如何確定原本的thread還在跑呢? 又如果可以確定thr
03/05 18:44, 2F
QQ 我是自己猜的 應該是thread沒錯

03/05 18:45, , 3F
ead還在跑 那應該有機會砍掉吧QQ
03/05 18:45, 3F

03/05 18:51, , 4F
在thread裡設flag,destroy時把flag值改掉?
03/05 18:51, 4F
這樣的話 thread runnable 裡面不就要很多地方設 flag? 不然手機還是要做一些白工 最後沒有update ListView的資料而已?

03/05 20:32, , 5F
這個scenario是android開發最機巴毛的地方之一阿...
03/05 20:32, 5F

03/05 22:43, , 6F
用asynctask 去管理會不會比較好 可搭配cancel
03/05 22:43, 6F
冏 好像不錯! 明天試試 謝謝大大們的指教! ※ 編輯: issuemylove 來自: 118.165.190.102 (03/06 00:26)

03/06 07:33, , 7F
可以用 handler 吃 runnable
03/06 07:33, 7F

03/06 11:40, , 8F
?? 樓上的意思我不太懂QQ
03/06 11:40, 8F

03/06 19:35, , 9F
應該是用handler post的意思
03/06 19:35, 9F

03/08 00:23, , 10F
Thread有interrupt(),try keep reference and control it
03/08 00:23, 10F

03/08 00:24, , 11F
或者丟到Thread pool對pool做關閉也行
03/08 00:24, 11F

03/08 11:05, , 12F
可是thread interrupt是要有一些狀態下才能interrupt
03/08 11:05, 12F

03/08 11:05, , 13F
不是嗎? (wait, sleep, join) 可是我的thread
03/08 11:05, 13F

03/08 11:06, , 14F
只是單純做網路下載,並沒有用到 wait, sleep, join
03/08 11:06, 14F

03/08 11:06, , 15F
等 function
03/08 11:06, 15F

03/09 02:44, , 16F
看到樓上的想起最近也在煩惱類似的事情...
03/09 02:44, 16F

03/09 02:45, , 17F
例如類似 .accept() 的 blocking code 怎麼 interrupt
03/09 02:45, 17F

03/09 13:56, , 18F
其實只要有 blocking 的動作, 最終(在API內部)還是會呼
03/09 13:56, 18F

03/09 13:57, , 19F
叫到 wait或sleep, 只是會以不同的 exception 表示
03/09 13:57, 19F

03/09 13:58, , 20F
API內部會去抓InterruptedException然後轉成別的
03/09 13:58, 20F

03/09 13:59, , 21F
例如socket的accept/read, 被 interrupt 時也會發出
03/09 13:59, 21F

03/09 13:59, , 22F
InterruptedIOException (不是 InterruptedException)
03/09 13:59, 22F

03/09 14:00, , 23F
如果想要定時離開 blocking 做別的事, 可以setSoTimeout
03/09 14:00, 23F

03/09 14:00, , 24F
就不會完全被 block 住
03/09 14:00, 24F

03/09 14:01, , 25F
另外如果你的code真的沒有呼任何blocking的API, 也可以
03/09 14:01, 25F

03/09 14:02, , 26F
自己去檢查 Thread.currentThread.isInterrupted()來知
03/09 14:02, 26F

03/09 14:02, , 27F
道thread是否有被 interrupt()
03/09 14:02, 27F

03/14 17:10, , 28F
最後我採用了邏輯設定的辦法QQ||| 感覺很笨
03/14 17:10, 28F

03/14 17:10, , 29F
但我想了很久還是不知道thread怎麼關 哈哈orz
03/14 17:10, 29F
文章代碼(AID): #1HDQodEp (AndroidDev)