Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách gửi Intent mở URL cụ thể trên trình duyệt Android

Giới thiệu

Ví dụ này minh họa cách sử dụng Intent.ACTION_VIEW để mở một URL cụ thể trên trình duyệt web mặc định của thiết bị Android.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (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"
    android:padding="8dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnOpenUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="GetUrlFromIntent"
        android:text="Mở Google.com" />

</RelativeLayout>

Bước 3: Code MainActivity (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 = "https://www.google.com";
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }
}

Bước 4: Manifest (androidManifest.xml)

<?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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút "Mở Google.com" → trình duyệt mặc định mở trang Google.

Cách gửi Intent mở URL cụ thể trên trình duyệt Android Cách gửi Intent mở URL cụ thể trên trình duyệt Android

Giải thích kỹ thuật

  • Intent.ACTION_VIEW: Action chung để "xem" dữ liệu (web, ảnh, video, map...).
  • Uri.parse(url): Chuyển chuỗi URL thành đối tượng Uri.
  • intent.setData(uri): Gán dữ liệu (URL) cho Intent.
  • startActivity(intent): Yêu cầu hệ thống tìm Activity phù hợp (trình duyệt) để xử lý.

Mở rộng & Trường hợp đặc biệt

1. Mở URL trong Custom Tab (Chrome Custom Tab) - Khuyến nghị cho UX tốt hơn

// Thêm dependency: implementation 'androidx.browser:browser:1.6.0'
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse("https://www.google.com"));

2. Mở trong WebView nội bộ app (giữ người dùng trong app)

WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com");

3. Xử lý khi không có app nào xử lý Intent (tránh crash)

if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent);
} else {
    Toast.makeText(this, "Không có trình duyệt nào được cài đặt", Toast.LENGTH_SHORT).show();
}

4. Mở các scheme khác

  • Điện thoại: tel:0123456789
  • SMS: sms:0123456789 hoặc smsto:0123456789?body=Hello
  • Email: mailto:email@example.com?subject=Tiêu đề&body=Nội dung
  • Google Maps: geo:latitude,longitude?q=địa_chỉ
  • Play Store: market://details?id=com.package.name