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

Cách phát hiện thiết bị là Phone hay Tablet trong Android

Giới thiệu

Bài viết này hướng dẫn cách xác định thiết bị đang chạy ứng dụng là điện thoại (Phone) hay máy tính bảng (Tablet) trong Android.

Các phương pháp

Phương pháp 1: TelephonyManager (Cũ, đơn giản)

Kiểm tra xem thiết bị có chức năng điện thoại (voice call) hay không.

package app.com.sample;

import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        detectDeviceTypeTelephony();
    }

    private void detectDeviceTypeTelephony() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if (Objects.requireNonNull(telephonyManager).getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
            showToast("Phát hiện: Bạn đang sử dụng Máy tính bảng (Tablet)");
        } else {
            showToast("Phát hiện: Bạn đang sử dụng Điện thoại (Phone)");
        }
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

Hạn chế:

  • Một số tablet có slot SIM (data only) vẫn báo PHONE_TYPE_NONE
  • Một số phone không có SIM slot hiếm khi gặp
  • Không phân biệt được tablet lớn vs phone to (phablet)

Phương pháp 2: Screen Size Category (Khuyên dùng)

Sử dụng Configuration.screenLayout để phân loại theo kích thước màn hình.

private void detectByScreenSize() {
    Configuration config = getResources().getConfiguration();
    int screenSize = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;

    String deviceType;
    switch (screenSize) {
        case Configuration.SCREENLAYOUT_SIZE_SMALL:
            deviceType = "Small (Phone nhỏ)";
            break;
        case Configuration.SCREENLAYOUT_SIZE_NORMAL:
            deviceType = "Normal (Phone tiêu chuẩn)";
            break;
        case Configuration.SCREENLAYOUT_SIZE_LARGE:
            deviceType = "Large (Tablet 7 inch / Phone lớn)";
            break;
        case Configuration.SCREENLAYOUT_SIZE_XLARGE:
            deviceType = "XLarge (Tablet 10 inch+)";
            break;
        default:
            deviceType = "Unknown";
    }

    showToast("Kích thước màn hình: " + deviceType);

    // Logic đơn giản: Large/XLarge = Tablet
    boolean isTablet = (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE)
                    || (screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE);
}

Phương pháp 3: Kết hợp Screen Size + Telephony (Tốt nhất)

public boolean isTablet(Context context) {
    // 1. Check screen size
    Configuration config = context.getResources().getConfiguration();
    int screenSize = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
    boolean isLargeScreen = (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE)
                         || (screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE);

    // 2. Check telephony (optional)
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    boolean hasTelephony = tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;

    // Tablet = màn hình lớn KHÔNG có telephony
    // Hoặc: màn hình lớn (bỏ qua telephony cho đơn giản)
    return isLargeScreen; // Hoặc: isLargeScreen && !hasTelephony
}

Phương pháp 4: Sử dụng thư viện (Material Components)

// Trong build.gradle
implementation 'com.google.android.material:material:1.10.0'

// Code
import com.google.android.material.resources.MaterialAttributes;

boolean isTablet = MaterialAttributes.isTablet(context);

Layout demo (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">

    <TextView
        android:id="@+id/tvDeviceType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Đang phát hiện thiết bị..."
        android:textAlignment="center"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

Manifest

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

    <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

Chạy trên phone và tablet (hoặc emulator) để thấy kết quả khác nhau.

Cách phát hiện thiết bị là Phone hay Tablet trong Android

Ứng dụng thực tế

  • Hiển thị layout khác nhau: res/layout-sw600dp/ cho tablet
  • Bật/tắt tính năng: multi-pane layout trên tablet
  • Analytics: Phân loại user agent
  • Quảng cáo: Hiển thị quảng cáo phù hợp kích thước

Kotlin Extension

fun Context.isTablet(): Boolean {
    val screenSize = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK
    return screenSize >= Configuration.SCREENLAYOUT_SIZE_LARGE
}

// Usage
if (context.isTablet()) { /* tablet layout */ } else { /* phone layout */ }