2017-11-08 4 views
0

오늘 토글 버튼을 사용하여 작업을 완료했습니다. 사용 설정 버튼을 누르면 모바일 데이터가 켜져 야하며 같은 버튼을 누르면 모바일 데이터가 꺼져 야합니다. 모든 작업을 완료했는데 사용 가능 버튼을 누르면 모바일 데이터가 유지됩니다. 사실 모든 명시 적 권한을 추가했습니다. 토글 버튼을 누르면 모바일 데이터가 켜져 야합니다. 제발 친구를 도우십시오. 그리고 내가 실수 한 곳을 알려주십시오. 여기에 XML과 Java 코딩을 묶었습니다. 친구들을 도와주세요. 미리 감사드립니다.토글 버튼을 사용하여 모바일 데이터를 켜고 끌 수있는 방법은 무엇입니까?

MainActivity.java :

import android.app.Activity; 
import android.content.Context; 
import android.net.ConnectivityManager; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.widget.ToggleButton; 
import android.os.Bundle; 

import java.lang.reflect.Field; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

public class MainActivity extends Activity{ 
    // constants 
    static final String STATUS_ON = "Mobile Data: Enable"; 
    static final String STATUS_OFF = "Mobile Data: Disable"; 

    static final String TURN_ON = "Enable"; 
    static final String TURN_OFF = "Disable"; 

    // controls 
    TextView TVMobileData; 
    ToggleButton tBMobileData; 



    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // load controls 
     TVMobileData=(TextView)findViewById(R.id.TVMobileData); 
     tBMobileData=(ToggleButton)findViewById(R.id.tBMobileData); 

     // set click event for button 
     tBMobileData.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // check current state first 
       boolean state = isMobileDataEnable(); 
       // toggle the state 
       if(state)toggleMobileDataConnection(false); 
       else toggleMobileDataConnection(true); 
       // update UI to new state 
       updateUI(!state); 
      } 
     }); 
    } 
    public void updateUI(boolean state) { 
     //set text according to state 
     if(state) { 
      TVMobileData.setText(STATUS_ON); 
      tBMobileData.setText(TURN_OFF); 
     } else { 
      TVMobileData.setText(STATUS_OFF); 
      tBMobileData.setText(TURN_ON); 
     } 
    } 
    public boolean isMobileDataEnable() { 
     boolean mobileDataEnabled = false; // Assume disabled 
     ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); 
     try { 
      Class cmClass = Class.forName(cm.getClass().getName()); 
      Method method = cmClass.getDeclaredMethod("getMobileDataEnabled"); 
      method.setAccessible(true); // Make the method callable 
      // get the setting for "mobile data" 
      mobileDataEnabled = (Boolean)method.invoke(cm); 
     } catch (Exception e) { 
      // Some problem accessible private API and do whatever error handling you want here 
     } 
     return mobileDataEnabled; 
    } 
    public boolean toggleMobileDataConnection(boolean ON) 
    { 
     try { 
      //create instance of connectivity manager and get system connectivity service 
      final ConnectivityManager conman = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); 
      //create instance of class and get name of connectivity manager system service class 
      final Class conmanClass = Class.forName(conman.getClass().getName()); 
      //create instance of field and get mService Declared field 
      final Field iConnectivityManagerField= conmanClass.getDeclaredField("mService"); 
      //Attempt to set the value of the accessible flag to true 
      iConnectivityManagerField.setAccessible(true); 
      //create instance of object and get the value of field conman 
      final Object iConnectivityManager = iConnectivityManagerField.get(conman); 
      //create instance of class and get the name of iConnectivityManager field 
      final Class iConnectivityManagerClass= Class.forName(iConnectivityManager.getClass().getName()); 
      //create instance of method and get declared method and type 
      final Method setMobileDataEnabledMethod= iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE); 
      //Attempt to set the value of the accessible flag to true 
      setMobileDataEnabledMethod.setAccessible(true); 
      //dynamically invoke the iConnectivityManager object according to your need (true/false) 
      setMobileDataEnabledMethod.invoke(iConnectivityManager, ON); 
     } catch (Exception e){ 
     } 
     return true; 
    } 
} 

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="arun.com.togglebuttonexample.MainActivity"> 

    <TextView 
     android:id="@+id/TVMobileData" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="90dp" 
     android:text="Mobile Data: Disable" 
     android:textColor="#1BD6E0" 
     android:textSize="40sp" /> 

    <ToggleButton 
     android:id="@+id/tBMobileData" 
     android:layout_width="225dp" 
     android:layout_height="225dp" 
     android:layout_centerInParent="true" 
     android:textSize="30sp" 
     android:textOff="Enable" 
     android:textOn="Disable" /> 
</RelativeLayout> 

의 AndroidManifest.xml : 당신은 떨어져 programmaticaly 안드로이드 4.4/아래에 모바일 데이터에 액세스 할 수 있습니다

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    package="arun.com.togglebuttonexample"> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> 
     <uses-permission android:name="android.permission.WRITE_SETTINGS"/> 

    <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> 
+0

[This] (https://stackoverflow.com/questions/26539445/the-setmobiledataenabled-method-is-no-longer-callable-as-of-android-l-and-later) – ADM

답변

0

하지만, 4.4 이상이어야합니다. 허가 확인을 위해 MODIFY_PHONE_STATE이 필요합니다. 이 권한은 시스템 또는 서명 앱에만 부여됩니다. 그래서 뿌리가없는 전화기에서는 작동하지 않습니다.