android中利用瀏覽器來開啟連結中含有中文的網頁問題

weixin_34402090發表於2012-07-16

android 中,利用瀏覽器來開啟網頁的做法為

String url_Str = "http://www.google.com.tw";
Uri uri = Uri.parse(url_Str);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent); 

但是若要在url後面加上引數則可能會造成中文亂碼問頭發生,解決方法為將引數利用URLEncoder.encode轉成utf8再傳送即可

String url_Str="http://www.yahoo.com/search?test="+URLEncoder.encode("字串","UTF-8");
Uri uri = Uri.parse(url_Str);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);

-------------------------------------------
以上做法為網上找到的方法。
但當要開啟的頁面的連線為一個引數,不固定的時候,如何進行處理的。
嘗試了

String url_Str=URLEncoder.encode(urlStr,"UTF-8");
Uri uri = Uri.parse(url_Str);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);

無法開啟,因為將網址中非中文的字元也進行了編碼的轉換。
解決方法為:

String urlStr = Uri.encode(workBlock.url,":/");
Uri u = Uri.parse(urlStr);
intent.setData(u);
startActivity(intent);

相關文章