url轉bitmap

看板AndroidDev作者 (瘋子)時間11年前 (2013/03/14 15:46), 編輯推噓4(4010)
留言14則, 5人參與, 最新討論串1/1
public static Bitmap getBitmap(String url) { Bitmap bm = null; try { URL aURL = new URL(url); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(new FlushedInputStream(is)); bis.close(); is.close(); } catch (Exception e) { e.printStackTrace(); Log.e("bitmap", "failed"); } finally { if (httpclient != null) { httpclient.close(); } } return bm; } 我傳入一個url卻一直跑 catch 那個url確定是圖片 沒問題 是不是連線或那裡有問題啊? 似乎是連線的問題 叫做StrictMode 他適用於ANDROID 2.3板以上 加以下規格就可以跑了 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() .build()); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.127.181

03/14 15:58, , 1F
已解決,= =
03/14 15:58, 1F

03/15 10:33, , 2F
解決了要寫解法啊qq
03/15 10:33, 2F

03/15 15:15, , 3F
好,但是我不知道為什麼要這樣
03/15 15:15, 3F
※ 編輯: loveyoualway 來自: 111.243.98.7 (03/15 15:17) ※ 編輯: loveyoualway 來自: 111.243.98.7 (03/15 15:18)

03/16 10:40, , 4F
要附上原本問題的 log 才有機會對得上問題與解法的關聯性
03/16 10:40, 4F

03/16 14:08, , 5F
有解答推, 也推樓上
03/16 14:08, 5F

03/16 21:11, , 6F
main thread 不能執行network <=StrictMode
03/16 21:11, 6F

03/16 21:12, , 7F
大約是這樣的限制
03/16 21:12, 7F

03/19 21:59, , 8F
main thread如果5秒沒回應就會ANR, 耗時的東西應該移到ba
03/19 21:59, 8F

03/19 21:59, , 9F
ckgroud thread,例如network, file IO, database...
03/19 21:59, 9F

03/19 22:01, , 10F
背後做完後如果需要更新畫面,再利用post給handler或view
03/19 22:01, 10F

03/19 22:01, , 11F
或runOnUi交給main thread
03/19 22:01, 11F

03/19 22:02, , 12F
也可以繼承AsyncTask來做
03/19 22:02, 12F

03/19 22:04, , 13F
如果backgroud thread可能使用頻繁,可用thread pool,
03/19 22:04, 13F

03/19 22:04, , 14F
或用一個使用HandlerThread's looper的Handler
03/19 22:04, 14F
文章代碼(AID): #1HGO1NH9 (AndroidDev)