只要直接把 Uri 帶進 Intent 啟動就可以了,
但是如果要用到 Post 來傳送資料的話,
可以使用以下這個方法。
String html = getPayHtml(); //取得要傳送的POST資料 String dataUri = "data:text/html," + URLEncoder.encode(html).replaceAll("\\+","%20"); Intent i = new Intent(); i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity")); i.setAction(Intent.ACTION_VIEW); i.setData(Uri.parse(dataUri)); startActivity(i);getPayHtml() 這個funtion是讀取要 Post 的 Form,
網頁放在 res/raw 下面
private String getPayHtml() { String html = readTrimRawTextFile(this, R.raw.round); return html; } private static String readTrimRawTextFile(Context ctx, int resId) { InputStream inputStream = ctx.getResources().openRawResource(resId); InputStreamReader inputreader = new InputStreamReader(inputStream); BufferedReader buffreader = new BufferedReader(inputreader); String line; StringBuilder text = new StringBuilder(); try { while ((line = buffreader.readLine()) != null) { text.append(line.trim()); } } catch (IOException e) { return null; } return text.toString(); }來看一下 round.html 寫了什麼?
postUrl是要傳送的目標網址,
name 和 value 改成要傳送的值。
<html> <body onLoad="document.getElementById('form').submit()"> <form id="form" target="_self" method="POST" action="postUrl"> <input type="hidden" name="howgo" value="2" /> <input type="hidden" name="id2" value="" /> <input type="hidden" name="go2sn" value="" /> <input type="hidden" name="id3" value="" /> <input type="hidden" name="go3sn" value="" /> </form> </body> </html>但是有些手機會發生找不到預設瀏覽器的問題,
所以 Intent 可以改成這樣:
String html = getPayHtml(); //取得要傳送的POST資料 String dataUri = "data:text/html," + URLEncoder.encode(html).replaceAll("\\+","%20"); Intent i = new Intent(); i.setComponent(getDefaultBrowserComponent(this)); //找出預設的瀏覽器 i.setAction(Intent.ACTION_VIEW); i.setData(Uri.parse(dataUri)); startActivity(i);
public static ComponentName getDefaultBrowserComponent(Context context) { Intent i = new Intent() .setAction(Intent.ACTION_VIEW) .setData(new Uri.Builder() .scheme("http") .authority("x.y.z") .appendQueryParameter("q", "x") .build() ); PackageManager pm = context.getPackageManager(); ResolveInfo default_ri = pm.resolveActivity(i, 0); // may be a chooser ResolveInfo browser_ri = null; ListrList = pm.queryIntentActivities(i, 0); for (ResolveInfo ri : rList) { if (ri.activityInfo.packageName.equals(default_ri.activityInfo.packageName) && ri.activityInfo.name.equals(default_ri.activityInfo.name) ) { return ri2cn(default_ri); } else if ("com.android.browser".equals(ri.activityInfo.packageName)) { browser_ri = ri; } } if (browser_ri != null) { return ri2cn(browser_ri); } else if (rList.size() > 0) { return ri2cn(rList.get(0)); } else if (default_ri == null) { return null; } else { return ri2cn(default_ri); } } private static ComponentName ri2cn(ResolveInfo ri) { return new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name); }