ภาพรวม
ตัวอย่างนี้สาธิตการใช้ Intent.ACTION_VIEW เพื่อเปิด URL ในเบราว์เซอร์เริ่มต้นของระบบ
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://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: เขียนโค้ดหลัก (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 = "https://www.google.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
ขั้นตอนที่ 4: AndroidManifest.xml (ต้องมีสิทธิ์ INTERNET)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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>
การทดสอบ
รันแอป กดปุ่ม "Get URL from Intent" จะเปิดเบราว์เซอร์ไปที่ google.com

