Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบ Network Roaming ใน Android

การตรวจสอบสถานะ Network Roaming ใน Android

ตัวอย่างสาธิตการใช้ TelephonyManager.isNetworkRoaming() เพื่อตรวจสอบว่าอุปกรณ์อยู่ในสถานะ Roaming หรือไม่

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project

ขั้นตอนที่ 2: Layout XML (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

ขั้นตอนที่ 3: AndroidManifest.xml

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

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application ...>
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

ขั้นตอนที่ 4: โค้ด Java (src/MainActivity.java)

package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 100;
    TextView textView;
    TelephonyManager telephonyManager;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        checkPermissionAndFetch();
    }

    private void checkPermissionAndFetch() {
        String[] perms = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION};
        boolean granted = true;
        for (String p : perms) {
            if (ActivityCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                granted = false; break;
            }
        }
        if (!granted) {
            ActivityCompat.requestPermissions(this, perms, PERMISSION_REQUEST_CODE);
        } else {
            fetchRoamingStatus();
        }
    }

    private void fetchRoamingStatus() {
        boolean isRoaming = telephonyManager.isNetworkRoaming();
        String roamingStatus = isRoaming ? "🔴 Roaming (อยู่ต่างเครือข่าย)" : "🟢 Home Network (เครือข่ายบ้าน)";

        StringBuilder sb = new StringBuilder();
        sb.append(roamingStatus).append("\n\n");
        sb.append("Network Operator: ").append(telephonyManager.getNetworkOperatorName()).append("\n");
        sb.append("Network Operator (Numeric): ").append(telephonyManager.getNetworkOperator()).append("\n");
        sb.append("Sim Operator: ").append(telephonyManager.getSimOperatorName()).append("\n");
        sb.append("Sim Operator (Numeric): ").append(telephonyManager.getSimOperator()).append("\n");
        sb.append("Network Country ISO: ").append(telephonyManager.getNetworkCountryIso()).append("\n");
        sb.append("Sim Country ISO: ").append(telephonyManager.getSimCountryIso()).append("\n");

        textView.setText(sb.toString());
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
            if (granted) fetchRoamingStatus();
            else textView.setText("Permission denied");
        }
    }
}

การทดสอบ

รันแอป อนุญาต Permission จะแสดงสถานะ Roaming พร้อมข้อมูลเครือข่ายเพิ่มเติม

วิธีตรวจสอบ Network Roaming ใน Android

Roaming คืออะไร?

  • Home Network: เครือข่ายของ SIM Card (เช่น AIS Thailand)
  • Roaming: เชื่อมต่อเครือข่ายอื่นนอกพื้นที่ Home (เช่น ไปต่างประเทศ ใช้เครือข่ายท้องถิ่น)
  • isNetworkRoaming() คืนค่า true เมื่อ Network Operator ≠ Sim Operator

ข้อมูลที่เกี่ยวข้องกับ Roaming

// ตรวจสอบ Data Roaming Setting (User เปิด/ปิดใน Settings)
boolean dataRoamingEnabled = telephonyManager.isDataRoamingEnabled(); // API 26+

// ตรวจสอบ Voice Roaming
boolean voiceRoaming = telephonyManager.isVoiceRoaming(); // API 31+ (Deprecated ในบาง API)

// Network Type ขณะ Roaming
int networkType = telephonyManager.getNetworkType(); // LTE, NR, WCDMA, GSM, etc.

กรณีการใช้งาน (Use Cases)

  • แจ้งเตือน User ก่อนใช้ Data Roaming (ค่าใช้จ่ายสูง)
  • ปิด Auto-sync/Background data เมื่อ Roaming
  • แสดงข้อความแจ้งเตือนใน App
  • Analytics: วัดการใช้งานต่างประเทศ
  • Enterprise: Enforce Policy (Block roaming data)

ตัวอย่าง: แจ้งเตือน User เมื่อ Roaming

if (telephonyManager.isNetworkRoaming()) {
    new AlertDialog.Builder(this)
        .setTitle("⚠️ Roaming Detected")
        .setMessage("คุณกำลังใช้งาน Roaming อาจมีค่าใช้จ่ายเพิ่มเติม ต้องการเปิดใช้งาน Data Roaming หรือไม่?")
        .setPositiveButton("เปิด", (d, w) -> {
            // นำไป Settings
            startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
        })
        .setNegativeButton("ปิด", null)
        .show();
}

ข้อจำกัด

  • ต้อง Permission READ_PHONE_STATE (+ LOCATION ในบาง API)
  • ค่าอาจไม่แม่นยำทันทีหลัง Boot/เปลี่ยน SIM (ต้องรอ Network Registration)
  • Wi-Fi Calling: อาจรายงาน Roaming แม้อยู่ในประเทศ (ขึ้นอยู่กับ Carrier)
  • Dual SIM: ต้องตรวจสอบแต่ละ Subscription แยกกัน

Dual SIM Roaming Check (API 22+)

SubscriptionManager subManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
List<SubscriptionInfo> subs = subManager.getActiveSubscriptionInfoList();
for (SubscriptionInfo sub : subs) {
    TelephonyManager tm = telephonyManager.createForSubscriptionId(sub.getSubscriptionId());
    boolean roaming = tm.isNetworkRoaming();
    Log.d(TAG, "SIM " + sub.getDisplayName() + " Roaming: " + roaming);
}