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

Cách mở trang Facebook từ ứng dụng Android bằng Kotlin

Giới thiệu

Hướng dẫn này trình bày cách mở trang Facebook (Facebook Page) từ ứng dụng Android: ưu tiên mở bằng ứng dụng Facebook (nếu đã cài), ngược lại mở bằng trình duyệt web. Sử dụng Intent và Uri với Kotlin.

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

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

Tạo project: File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:onClick="fbClick"
        android:text="Open Facebook" />

</LinearLayout>

Bước 3: Xử lý logic (src/MainActivity.kt)

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun fbClick(view: View) {
        startActivity(getOpenFacebookIntent())
    }

    private fun getOpenFacebookIntent(): Intent? {
        return try {
            // Kiểm tra app Facebook có cài đặt không
            packageManager.getPackageInfo("com.facebook.katana", 0)
            // Mở bằng Facebook App (deep link)
            Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/426253597411506"))
        } catch (e: Exception) {
            // Fallback: Mở bằng trình duyệt web
            Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/appetizerandroid"))
        }
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.q11">

    <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 "Open Facebook":

  • Nếu đã cài app Facebook → Mở app Facebook tại trang chỉ định.
  • Nếu chưa cài → Mở trình duyệt web tại trang Facebook.

Giải thích Deep Link Facebook

Loại Scheme/URL Ví dụ
Trang (Page) fb://page/<PAGE_ID> fb://page/426253597411506
Hồ sơ (Profile) fb://profile/<USER_ID> fb://profile/123456789
Bài viết (Post) fb://post/<POST_ID> fb://post/987654321
Nhóm (Group) fb://group/<GROUP_ID> fb://group/111222333
Web fallback https://facebook.com/<username_or_id> https://www.facebook.com/appetizerandroid

Lấy Page ID

Truy cập: https://findmyfbid.com/ hoặc https://lookup-id.com/, nhập URL trang Facebook để lấy ID số.

Cách hiện đại: Package Visibility (Android 11+)

Từ Android 11 (API 30), getPackageInfo yêu cầu khai báo <queries> trong Manifest:

<manifest ...>
    <queries>
        <package android:name="com.facebook.katana" />
        <package android:name="com.facebook.lite" />
    </queries>
    ...
</manifest>

Cải tiến: Hỗ trợ Facebook Lite

private fun getOpenFacebookIntent(): Intent? {
    val pageId = "426253597411506"
    val webUrl = "https://www.facebook.com/appetizerandroid"
    
    val fbPackages = listOf("com.facebook.katana", "com.facebook.lite")
    
    for (pkg in fbPackages) {
        try {
            packageManager.getPackageInfo(pkg, 0)
            return Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/$pageId"))
        } catch (e: PackageManager.NameNotFoundException) {
            // Thử package tiếp theo
        }
    }
    
    // Không có app FB nào -> mở web
    return Intent(Intent.ACTION_VIEW, Uri.parse(webUrl))
}

Lưu ý

  • Luôn cung cấp fallback web URL.
  • Deep link scheme fb:// có thể thay đổi theo phiên bản app Facebook.
  • Test trên thiết bị thật (emulator thường không cài Facebook).