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

วิธีปิด/เปิด Mobile Data ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการควบคุม Mobile Data ผ่าน Reflection API แต่มีข้อจำกัดสำคัญ

⚠️ ข้อจำกัดสำคัญ

  • ต้องการสิทธิ์ MODIFY_PHONE_STATE ซึ่งเป็น System/Signature permission เท่านั้น
  • แอปทั่วไป ไม่สามารถ ใช้งานได้จริงบน Android 5.0+ (API 21+)
  • เมธอด setMobileDataEnabled() หยุดทำงานผ่าน Reflection ตั้งแต่ Android 5.0
  • ทำงานได้เฉพาะบน Android 2.1-4.4 (API 7-19) และต้อง Root

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

เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    <Switch
        android:id="@+id/switchData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Mobile Data" />
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java) - สำหรับการศึกษาเท่านั้น

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.Switch;
import java.lang.reflect.Method;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    Switch mySwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySwitch = findViewById(R.id.switchData);
        mySwitch.setChecked(getMobileDataState());
        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setMobileDataState(isChecked);
            }
        });
    }

    public void setMobileDataState(boolean mobileDataEnabled) {
        try {
            TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            Method setMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass()
                .getDeclaredMethod("setDataEnabled", boolean.class);
            setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
        } catch (Exception ex) {
            Log.e("MainActivity", "Error setting mobile data state", ex);
        }
    }

    public boolean getMobileDataState() {
        try {
            TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            Method getMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass()
                .getDeclaredMethod("getDataEnabled");
            return (boolean) getMobileDataEnabledMethod.invoke(telephonyService);
        } catch (Exception ex) {
            Log.e("MainActivity", "Error getting mobile data state", ex);
        }
        return false;
    }
}

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

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

การทดสอบ

รันแอป Switch จะแสดงสถานะ แต่ จะไม่สามารถเปิด/ปิด Mobile Data จริงได้ บน Android รุ่นใหม่

วิธีปิด/เปิด Mobile Data ใน Android

ทางเลือกที่แนะนำ

ใช้ Intent เปิดหน้าตั้งค่า Mobile Data ให้ผู้ใช้ตั้งค่าเอง:

Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
// หรือ
Intent intent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
startActivity(intent);