如何在 Android 中傳送意圖讓瀏覽器開啟指定 URL?
本示例演示瞭如何傳送意圖讓瀏覽器開啟 android 中的特定 URL。
步驟 1 − 在 Android Studio 中建立新專案,轉到檔案 ⇒ 新專案,然後填寫所有必需資訊以建立新專案。
步驟 2 − 新增以下程式碼到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <Button android:onClick="GetUrlFromIntent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get URL from Intent" android:layout_centerInParent="true"/> </RelativeLayout>
步驟 3 − 新增以下程式碼到 src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void GetUrlFromIntent(View view) { String url = "http://www.google.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }
步驟 4 − 新增以下程式碼到 androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
我們來嘗試執行一下你的應用程式。我假設你已經將真正的 Android 移動裝置連線到了計算機。要從 android studio 執行應用程式,請開啟其中一個專案的活動檔案,然後單擊工具欄上的執行 圖示。選擇你的移動裝置作為選項,然後檢視你的移動裝置,它將顯示你的預設螢幕 −
點選 此處 下載專案程式碼。
廣告