[Android] 如何呼叫Android Browser Activity開啟URL


Activity之間是透過Intent物件進行activate與傳遞訊息,包括相同App內的Explicit Intent以及不同App間的Implicit Intent,也因為這個機制,App可以呼叫系統或是其它第三方所提供的Activity的服務,例如:播話介面、相機…等等,僅需要透過Intent物件設定欲執行的動作、資料與類型,system launcher會列出符合相關條件的Activity,如果有多個就會列表供User選擇。

因此,如果App需要一個顯示URL內容的功能時,開發者將不用重新撰寫一個,而可以直接利用Android的Browser來達成目標,本文將簡單示範如何將Google翻譯URL透過瀏覽器顯示。

程式碼說明

以下範例將會提供一個EditText供User輸入URL,在按下Button後將會呼叫Android瀏覽器顯示該網頁翻譯後的結果。

一、定義Layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="URL:" 
     android:textSize="18sp"    
    />
 <EditText 
  android:id="@+id/url_txt"
  android:layout_width="130dp"
  android:layout_height="wrap_content"    
 />
 <Button 
  android:text="Send"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
     android:onClick="activateBrowser"    
 />
</LinearLayout>
二、實作呼叫Browser Activity功能,透過Implicit Intent帶入ACTION_VIEW與目標Url,Action參數ACTION_VIEW意指顯示特定類型資料給User,系統會根據Data Type呼叫適當的Activity來顯示資料。
private EditText urlTxt;

public void activateBrowser(View v){
 urlTxt = (EditText)findViewById(R.id.url_txt);
 Intent intent = 
new Intent(Intent.ACTION_VIEW,Uri.parse(
"http://translate.google.com.tw/translate?u="+urlTxt.getText()));
 startActivity(intent);
}

留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

【海外婚紗】造型篇-我的超人新祕Sunny-Yang