作者issuemylove (skill)
看板AndroidDev
標題[問題] 程式關閉 thread 還是跑
時間Tue Mar 5 16:28:20 2013
想請教各位大大
我的app主要在實作
由 listView 從網路上拿資料
拿資料必須要經由 "thread" 從事網路存取
可是如果thread 並沒拿到資料
我此時立刻將app關閉了
再重複開啟 此時 thread 一樣會跑...
(就是會存在兩個thread,造成資料拿兩遍)
ListView 就會重複出現相同的 entry view
請問要怎樣解決這樣的問題QQ
ps. 應該不需要附加程式碼吧? 謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.163.3.187
1F:→ asadman1523:最近也有遇到,似乎邏輯設定要好,thread讓他自動結束 03/05 18:42
是類似這樣嗎?
宣告 static boolean threadOn = false;
if( not threadOn){
threadOn = true
thread run
}
thread running is end => threadOn = false;
2F:→ qweqweqweqwe:你如何確定原本的thread還在跑呢? 又如果可以確定thr 03/05 18:44
QQ 我是自己猜的 應該是thread沒錯
3F:→ qweqweqweqwe:ead還在跑 那應該有機會砍掉吧QQ 03/05 18:45
4F:推 motors55:在thread裡設flag,destroy時把flag值改掉? 03/05 18:51
這樣的話 thread runnable 裡面不就要很多地方設 flag?
不然手機還是要做一些白工 最後沒有update ListView的資料而已?
5F:→ NewSpec:這個scenario是android開發最機巴毛的地方之一阿... 03/05 20:32
6F:推 sdyy:用asynctask 去管理會不會比較好 可搭配cancel 03/05 22:43
冏 好像不錯! 明天試試
謝謝大大們的指教!
※ 編輯: issuemylove 來自: 118.165.190.102 (03/06 00:26)
7F:推 changyuheng:可以用 handler 吃 runnable 03/06 07:33
8F:→ issuemylove:?? 樓上的意思我不太懂QQ 03/06 11:40
9F:→ qweqweqweqwe:應該是用handler post的意思 03/06 19:35
10F:推 samsonjr:Thread有interrupt(),try keep reference and control it 03/08 00:23
11F:→ samsonjr:或者丟到Thread pool對pool做關閉也行 03/08 00:24
12F:→ issuemylove:可是thread interrupt是要有一些狀態下才能interrupt 03/08 11:05
13F:→ issuemylove:不是嗎? (wait, sleep, join) 可是我的thread 03/08 11:05
14F:→ issuemylove:只是單純做網路下載,並沒有用到 wait, sleep, join 03/08 11:06
15F:→ issuemylove:等 function 03/08 11:06
16F:推 ChonPiggy:看到樓上的想起最近也在煩惱類似的事情... 03/09 02:44
17F:→ ChonPiggy:例如類似 .accept() 的 blocking code 怎麼 interrupt 03/09 02:45
18F:推 MetalChao:其實只要有 blocking 的動作, 最終(在API內部)還是會呼 03/09 13:56
19F:→ MetalChao:叫到 wait或sleep, 只是會以不同的 exception 表示 03/09 13:57
20F:→ MetalChao:API內部會去抓InterruptedException然後轉成別的 03/09 13:58
21F:→ MetalChao:例如socket的accept/read, 被 interrupt 時也會發出 03/09 13:59
22F:→ MetalChao:InterruptedIOException (不是 InterruptedException) 03/09 13:59
23F:→ MetalChao:如果想要定時離開 blocking 做別的事, 可以setSoTimeout 03/09 14:00
24F:→ MetalChao:就不會完全被 block 住 03/09 14:00
25F:→ MetalChao:另外如果你的code真的沒有呼任何blocking的API, 也可以 03/09 14:01
26F:→ MetalChao:自己去檢查 Thread.currentThread.isInterrupted()來知 03/09 14:02
27F:→ MetalChao:道thread是否有被 interrupt() 03/09 14:02
28F:→ issuemylove:最後我採用了邏輯設定的辦法QQ||| 感覺很笨 03/14 17:10
29F:→ issuemylove:但我想了很久還是不知道thread怎麼關 哈哈orz 03/14 17:10