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

วิธีดึงข้อมูลบริการ SIM (Service State) ใน Android

ภาพรวม

บทความนี้สาธิตวิธีดึงข้อมูลสถานะบริการเครือข่ายของ SIM (Service State) เช่น สัญญาณ, โรมมิ่ง, ชนิดเครือข่าย ผ่าน TelephonyManager.getServiceState()

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (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:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:lineSpacingExtra="4dp" />

</LinearLayout>

ใช้ textSize เล็กลง และเพิ่ม lineSpacing เพื่ออ่านง่ายขึ้น เพราะข้อมูล ServiceState มีหลายบรรทัด

ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)

package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 100;
    private TextView textView;
    private TelephonyManager telephonyManager;

    @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);

        if (checkPermissions()) {
            showServiceState();
        } else {
            requestPermissions();
        }
    }

    private boolean checkPermissions() {
        return ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissions() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_PHONE_STATE},
                PERMISSION_REQUEST_CODE);
    }

    private void showServiceState() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        ServiceState serviceState = telephonyManager.getServiceState();
        StringBuilder info = new StringBuilder();

        info.append("สถานะ: ").append(getServiceStateName(serviceState.getState())).append("\n");
        info.append("โปรโตคอล: ").append(getRadioTechName(serviceState.getRadioTechnology())).append("\n");
        info.append("โรมมิ่ง: ").append(serviceState.getRoaming() ? "ใช่" : "ไม่").append("\n");
        info.append("Operator (Alpha): ").append(serviceState.getOperatorAlphaLong()).append("\n");
        info.append("Operator (Numeric): ").append(serviceState.getOperatorNumeric()).append("\n");
        info.append("CSS (Cell Signal Strength): ").append(serviceState.getCssIndicator()).append("\n");

        // Cell Info (ต้องการ.permission.ACCESS_FINE_LOCATION หรือ ACCESS_COARSE_LOCATION)
        // List cellInfoList = telephonyManager.getAllCellInfo();
        // if (cellInfoList != null) { ... }

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

    private String getServiceStateName(int state) {
        switch (state) {
            case ServiceState.STATE_IN_SERVICE: return "ในบริการ (In Service)";
            case ServiceState.STATE_OUT_OF_SERVICE: return "นอกบริการ (Out of Service)";
            case ServiceState.STATE_EMERGENCY_ONLY: return "ฉุกเฉินเท่านั้น (Emergency Only)";
            case ServiceState.STATE_POWER_OFF: return "ปิดเครื่อง/ไม่มีสัญญาณ (Power Off)";
            default: return "ไม่ทราบ (" + state + ")";
        }
    }

    private String getRadioTechName(int tech) {
        switch (tech) {
            case ServiceState.RADIO_TECHNOLOGY_GSM: return "GSM";
            case ServiceState.RADIO_TECHNOLOGY_CDMA: return "CDMA";
            case ServiceState.RADIO_TECHNOLOGY_LTE: return "LTE (4G)";
            case ServiceState.RADIO_TECHNOLOGY_NR: return "NR (5G)";
            case ServiceState.RADIO_TECHNOLOGY_HSPA: return "HSPA";
            case ServiceState.RADIO_TECHNOLOGY_HSPAP: return "HSPA+";
            case ServiceState.RADIO_TECHNOLOGY_TD_SCDMA: return "TD-SCDMA";
            case ServiceState.RADIO_TECHNOLOGY_IWLAN: return "IWLAN (WiFi Calling)";
            case ServiceState.RADIO_TECHNOLOGY_LTE_CA: return "LTE Carrier Aggregation";
            default: return "ไม่ทราบ (" + tech + ")";
        }
    }

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

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

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- สำหรับ Cell Info ต้องเพิ่ม -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- หรือ -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

ข้อมูลที่ได้จาก ServiceState

  • สถานะเครือข่าย (In Service, Out of Service, Emergency Only)
  • เทคโนโลยีวิทยุ (GSM, LTE, 5G NR, HSPA, CDMA, ฯลฯ)
  • สถานะโรมมิ่ง
  • ชื่อผู้ให้บริการ (Operator Name)
  • รหัสผู้ให้บริการ (MCC+MNC)
  • ระดับสัญญาณ (CSS Indicator)

หมายเหตุ

  • Android 12+ ต้องการ READ_PHONE_STATE + READ_PRECISE_PHONE_STATE สำหรับข้อมูลบางอย่าง
  • ข้อมูล Cell Info ต้องการ Location Permission
  • บน Emulator อาจไม่แสดงข้อมูลจริงได้