作者Ferich (純粹的透明)
看板AndroidDev
標題[問題] android thread實作問題
時間Tue Oct 30 13:52:41 2012
已爬過文 還是不甚理解 thread的宣告與用法
為何要用thread 主要是因為手上的手機是xs 為版本4.0.4
在httppost上無法寫入
在網路上看的解法是 需要寫入thread 給副thread去執行 而非main thread
(如有錯誤 請協助修正)
所以小弟來問thread的問題
主要是由一個按鈕按下去 傳一個值給function 讓他去執行httppost這件事情
按鈕按下去
renew=(Button) findViewById(R.id.update);
renew.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable(){
public void run(){
post(regId);
}
}).start();
Toast.makeText(DemoActivity.this, "send ok", Toast.LENGTH_LONG).show();
}
});
跟function接口
private String post(String id){
balabala
}
------------------------------------
在非4.0的手機上
在沒寫進thread時 按下按鈕直接 post(regId);
是可以執行寫入成功的
請問 這樣的thread 似乎按下按鈕 就會當掉
是有什麼問題
還是小弟把thread想太簡單了
以上.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.34.130.81
※ 編輯: Ferich 來自: 1.34.130.81 (10/30 13:55)
1F:→ realmeat:感覺要透過handler, thread送出msg由handler執行 10/30 15:00
2F:→ Ferich:請指教 寫了幾種寫法 debug直接都跳過thread.. 10/30 15:10
3F:→ Ferich:想法是 thread要宣告在onclick內 去呼叫function給值 10/30 15:11
4F:→ transwrap:post會不會成功跟寫在哪個thread沒有關係~ 10/30 15:14
5F:→ transwrap:只是post寫在main thread會讓使用者有卡住的感覺 10/30 15:15
6F:→ realmeat:最近才開始碰anrdroid, 得到的訊息是非main thread沒法控 10/30 15:17
7F:→ realmeat:制UI上的動作, 只能靠handler來控制 10/30 15:17
8F:→ realmeat:thread丟出msg, msg由handler接收後執行 10/30 15:17
9F:推 transwrap:post不是ui動作 所以要寫在哪個thread都可(包括main) 10/30 15:21
10F:→ transwrap:如果以前把post寫在main thread ok但是現在不行 10/30 15:25
11F:→ transwrap:我會猜是你用的http post library有問題 10/30 15:26
12F:→ transwrap:而不是因為你沒有另外開一個thread跑post所以才失敗 10/30 15:27
13F:→ Ferich:我沒用httppost的lib耶 是指android-support-v4.jar嗎? 10/30 15:31
14F:→ realmeat:所以在非main thread內call Toast算是合規則嗎? 10/30 15:34
15F:→ realmeat:眼花了, 看錯行 XD 10/30 15:38
16F:→ transwrap:如果不熟android我建議就先把post弄到動就好 10/30 15:42
17F:→ transwrap:你的程式裡面又有AsyncTask又有thread 10/30 15:43
18F:→ transwrap:但是這兩個本質上是一樣的東西 應該只要選一種用 10/30 15:43
19F:→ Ferich:以不用thread的方式 android非4.0的 都寫得進去 10/30 15:43
20F:→ transwrap:你不如先開一個新專案把post弄到動以後再繼續加東西 10/30 15:44
21F:→ transwrap:然後用Log.d debug 很多toast(ui)在非main thread 10/30 15:46
22F:→ transwrap:toast在其他thread應該是不會跳出來 10/30 15:48
23F:→ transwrap:所以不要用toast debug 10/30 15:49
24F:→ realmeat:是不會, 不過有的狀況會掛 10/30 15:49
25F:→ realmeat:死機logcat會給訊息, toast在非主thread有時掛有時不會 10/30 15:50
26F:→ realmeat:有的時候秀出warnning, 有時就當掉了 10/30 15:51
27F:→ transwrap:我沒試過toast在非main thread但是就算會動還是是很違規 10/30 15:52
28F:→ Ferich:找到問題了.. 就單純把post()內的toast拿掉 就過了... 10/30 16:18
※ 編輯: Ferich 來自: 1.34.130.81 (10/31 09:26)