2014年4月1日 星期二

Mobile network settings control

This topic is guilding Android developer to change and access mobile network settings in Android phone.

To changing and accessing mobile need to add two permissions as following:
  • android.permission.CHANGE_NETWORK_STATE
  • android.permission.ACCESS_NETWORK_STATE
In MobileSettings.java:
package com.example.mobilenetworkcontrol;

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

import android.content.Context;
import android.net.ConnectivityManager;

public class MobileSettings {
 /**add permission:
  * 1. android.permission.CHANGE_NETWORK_STATE
  * 2. android.permission.ACCESS_NETWORK_STATE
  * **/
 Context mContext;
 public MobileSettings(Context context){
  mContext = context;
 }
 /**
  * Check mobile network is enabled or not.
  * @return true if mobile is enabled, otherwise false.
  */
 public boolean isEnabled()
 {
   boolean mobileDataEnabled = false; // Assume disabled
      ConnectivityManager cm = (ConnectivityManager) mContext.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
          // TODO do whatever error handling you want here
      }
      return mobileDataEnabled;
 }
 /**
  * Enabling or disabling the mobile network.
  * @param enable true for turning on the mobile network. false for turning of the mobile network.
  */
 public void setEnabled(boolean enable){
  final ConnectivityManager conman = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        Class<?> conmanClass = null;
  try { conmanClass = Class.forName(conman.getClass().getName());}
  catch (ClassNotFoundException e) {e.printStackTrace();}
        Field iConnectivityManagerField = null;
  try {iConnectivityManagerField = conmanClass.getDeclaredField("mService");}
  catch (SecurityException e1) {e1.printStackTrace(); }
  catch (NoSuchFieldException e1) {e1.printStackTrace();}
        iConnectivityManagerField.setAccessible(true);
        Object iConnectivityManager = null;
  try {iConnectivityManager = iConnectivityManagerField.get(conman);}
  catch (IllegalArgumentException e) {e.printStackTrace();}
  catch (IllegalAccessException e) {e.printStackTrace();}
        Class<?> iConnectivityManagerClass = null;
  try {iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());}
  catch (ClassNotFoundException e) {e.printStackTrace();}
        Method setMobileDataEnabledMethod = null;
  try {setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);}
  catch (SecurityException e1) {e1.printStackTrace();}
  catch (NoSuchMethodException e1) {e1.printStackTrace();}
        setMobileDataEnabledMethod.setAccessible(true);
        try {setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);}
        catch (IllegalArgumentException e) {e.printStackTrace();}
        catch (IllegalAccessException e) {e.printStackTrace();}
        catch (InvocationTargetException e) {e.printStackTrace();}
 }
}


In MainActivity.java:
package com.example.mobilenetworkcontrol;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

public class MainActivity extends Activity implements OnCheckedChangeListener{
 Switch sw_mobile;
 MobileSettings mMobileSettings;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // get the UI object.
  sw_mobile = (Switch) this.findViewById(R.id.switch_mobile);
  sw_mobile.setOnCheckedChangeListener(this);
  // mobile settings object
  mMobileSettings = new MobileSettings(this);
  // check mobile switch.
  boolean mobileEnabled = mMobileSettings.isEnabled();
  sw_mobile.setChecked(mobileEnabled);
 }

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  if(buttonView == sw_mobile){
   if(isChecked == true){
    //turn on the mobile network
    mMobileSettings.setEnabled(true);
   }
   else{
    //turn off the mobile network
    mMobileSettings.setEnabled(false);
   }
  }//if(buttonView == sw_mobile)
 }
}

In activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="#000000">



        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:layout_marginTop="10dp"
                android:orientation="horizontal" >

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/text_mobile"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:text="Mobile Network"
                        android:textColor="#FFFFFFFF"
                        android:textSize="26dp" />

                </LinearLayout>

                <Switch
                    android:id="@+id/switch_mobile"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentTop="true" />

            </RelativeLayout>

        </LinearLayout>


</RelativeLayout>

In AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mobilenetworkcontrol"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mobilenetworkcontrol.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

沒有留言 :

張貼留言