บทความนี้สาธิตวิธีเปิดเว็บไซต์ในเบราว์เซอร์เริ่มต้นของ Android จากแอปพลิเคชันของคุณ โดยใช้ Intent.ACTION_VIEW พร้อม URI
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project แล้วกรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)
เพิ่มปุ่มสำหรับเปิดเว็บไซต์ใน res/layout/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"
tools:context=".MainActivity">
<Button
android:id="@+id/btnAmazon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Amazon"
android:textStyle="bold" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
ใช้ Intent เพื่อเปิด URL ในเบราว์เซอร์:
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btnAmazon);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.amazon.com";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
ขั้นตอนที่ 4: สิทธิ์ใน AndroidManifest.xml
ต้องเพิ่มสิทธิ์ INTERNET (แม้จะไม่จำเป็นสำหรับการเปิดเบราว์เซอร์ภายนอก แต่นิยมเพิ่มไว้):
<uses-permission android:name="android.permission.INTERNET" />
คำอธิบายการทำงาน
- Intent.ACTION_VIEW - แสดงเนื้อหา (ในที่นี้คือเว็บเพจ)
- Uri.parse(url) - แปลงสตริง URL เป็น URI object
- startActivity(intent) - เริ่มกิจกรรมใหม่ (จะเปิดเบราว์เซอร์)
ข้อควรระวัง
- ควรใช้
https://แทนhttps://เพื่อความปลอดภัย - หากไม่มีเบราว์เซอร์ติดตั้ง ระบบจะแสดงข้อผิดพลาด
- สามารถใช้
Intent.createChooser()เพื่อให้ผู้ใช้เลือกแอปที่ต้องการเปิด
ตัวอย่างการใช้ Chooser (แนะนำ)
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(Intent.createChooser(intent, "เปิดด้วย..."));