개요
이 예제는 안드로이드에서 프로그래밍 방식으로 모바일 데이터를 비활성화(또는 활성화)하는 방법을 다룹니다.
먼저 알아두어야 할 중요한 사항이 있습니다. 루팅(rooting)되지 않은 일반 기기에서는 앱이 임의로 모바일 데이터를 켜거나 끄는 것이 원칙적으로 불가능합니다. 이 작업을 수행하려면 MODIFY_PHONE_STATE 권한이 필요한데, 해당 권한은 시스템 앱 또는 시그니처(signature) 앱에만 부여되기 때문입니다.
또한 setMobileDataEnabled() 메서드는 더 이상 리플렉션(reflection)을 통해 호출할 수 없습니다. 과거에는 Android 2.1(API 7)부터 Android 4.4(API 19)까지 리플렉션으로 호출이 가능했지만, Android 5.0(Lollipop) 이후부터는 루팅된 기기에서도 이 메서드를 직접 호출할 수 없게 되었습니다.
구현 단계
1단계: 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성
res/layout/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 코드 작성
src/MainActivity.java에 아래 코드를 추가합니다. 스위치(Switch) 위젯의 상태 변화에 따라 TelephonyManager의 setDataEnabled() / getDataEnabled() 메서드를 리플렉션으로 호출하여 모바일 데이터 상태를 제어합니다.
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) (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>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 대상 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.
