Android 系統開關,wifi、手電筒等的開關

yne7 9年前發布 | 8K 次閱讀 Java Android

  • wifi是否開啟
  • wifi開關
  • 藍牙是否開啟
  • 藍牙開關
  • 是否開啟自動旋轉
  • 屏幕旋轉開關
  • 是否開啟同步
  • 同步開關
  • 屏幕亮度切換
  • 設置屏幕亮度
  • 是否開啟飛行模式
  • 飛行模式開關
  • 是否開啟數據連接
  • 數據連接開關
  • 情景模式切換
  • 是否開啟gps
  • gps開關
  • 鎖屏
  • 重啟
  • 關機
  • 是否開啟了閃光燈
  • 閃光燈開關
  • 閃光燈開關2
  • 跳轉到系統設置
  • 跳轉到系統app管理
  • 跳轉到系統顯示設置
  • 跳轉到系統聲音設置
  • 跳轉到系統日期設置
  • 跳轉到系統位置設置
  • 跳轉到系統同步設置
  • 跳轉到系統輸入設置
  • 調大媒體音量

package android.widget;

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

import android.bluetooth.BluetoothAdapter; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.location.LocationManager; import android.media.AudioManager; import android.net.ConnectivityManager; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.PowerManager; import android.os.SystemClock; import android.provider.Settings; import android.provider.Settings.Secure; import android.provider.Settings.SettingNotFoundException; import android.widget.Toast;

public class SystemSwitchUtils { private Context context; private WifiManager mWifiManager; private BluetoothAdapter mBluetoothAdapter; private ConnectivityManager connManager; private PowerManager mPowerManager; private AudioManager mAudioManager; private static Camera camera;

private final int LIGHT_NORMAL = 64;
private final int LIGHT_50_PERCENT = 127;
private final int LIGHT_75_PERCENT = 191;
private final int LIGHT_100_PERCENT = 255;
private final int LIGHT_AUTO = 0;
private final int LIGHT_ERR = -1;

private static SystemSwitchUtils util;

public static void getInstance(Context context){
    if (util==null) {
        util=new SystemSwitchUtils(context);
    }


}

private SystemSwitchUtils(Context context) {
    super();
    this.context = context;
}

/**
 * wifi是否開啟
 * @return
 */
public boolean isWifiOn() {
    if (mWifiManager == null) {
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
    }
    return mWifiManager.isWifiEnabled();
}

/**
 * wifi開關
 */
public void wifiUtils() {

    if (isWifiOn()) {
        // 關閉Wifi,按鈕顯示開啟
        mWifiManager.setWifiEnabled(false);
        Toast.makeText(context, "關閉wifi", Toast.LENGTH_SHORT).show();
    } else {
        // 開啟Wifi,按鈕顯示關閉
        mWifiManager.setWifiEnabled(true);

        Toast.makeText(context, "開啟wifi", Toast.LENGTH_SHORT).show();
    }

}

/**
 * 藍牙是否開啟
 * @return
 */
public boolean isBlueToothOn() {
    if (mBluetoothAdapter == null) {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }
     switch (mBluetoothAdapter.getState()) {
     case BluetoothAdapter.STATE_ON:
     return true;

     case BluetoothAdapter.STATE_TURNING_ON:
     return true;
     case BluetoothAdapter.STATE_OFF:
     return false;
     case BluetoothAdapter.STATE_TURNING_OFF:
     return false;
     }
    return false;
}

/**
 * 藍牙開關
 */
public void bluetoothUtils() {

    if (isBlueToothOn()) {
        mBluetoothAdapter.disable();
        Toast.makeText(context, "關閉藍牙", Toast.LENGTH_SHORT).show();
    } else {
        mBluetoothAdapter.enable();
        Toast.makeText(context, "開啟藍牙", Toast.LENGTH_SHORT).show();
    }

}

/**
 * 是否開啟自動旋轉
 * @return
 */
public boolean isRotationOn() {
    int status = 0;

    try {
        status = android.provider.Settings.System.getInt(
                context.getContentResolver(),
                android.provider.Settings.System.ACCELEROMETER_ROTATION);
    } catch (SettingNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // 設置status的值改變屏幕旋轉設置
    if (status == 0) {
        return false;
    } else {
        return true;
    }

}

/**
 * 屏幕旋轉開關
 */
public void rotationUtils() {
    int status = 0;

    Uri uri = android.provider.Settings.System
            .getUriFor("accelerometer_rotation");
    // 設置status的值改變屏幕旋轉設置
    if (!isRotationOn()) {
        status = 1;
        Toast.makeText(context, "開啟旋轉", Toast.LENGTH_SHORT).show();
    } else if (status == 1) {
        status = 0;
        Toast.makeText(context, "關閉旋轉", Toast.LENGTH_SHORT).show();
    }
    android.provider.Settings.System.putInt(context.getContentResolver(),
            "accelerometer_rotation", status);
    // 通知改變
    context.getContentResolver().notifyChange(uri, null);

}

/**
 * 是否開啟同步
 * @return
 */
@SuppressWarnings("deprecation")
public boolean isSyncSwitchOn() {
    if (connManager == null) {
        connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    return connManager.getBackgroundDataSetting()
            && ContentResolver.getMasterSyncAutomatically();
}

/**
 * 同步開關
 */
public void syncSwitchUtils() {

    if (isSyncSwitchOn()) {
        Toast.makeText(context, "關閉同步", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(context, "開啟同步", Toast.LENGTH_SHORT).show();
    }
    ContentResolver.setMasterSyncAutomatically(!isSyncSwitchOn());

}

/**
 * 屏幕亮度切換
 */
public void brightnessSwitchUtils() {

    int light = 0;
    ContentResolver cr = context.getContentResolver();
    try {
        boolean auto = Settings.System.getInt(cr,
                Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;

        if (!auto) {
            light = android.provider.Settings.System.getInt(cr,
                    Settings.System.SCREEN_BRIGHTNESS, -1);
            if (light > 0 && light <= LIGHT_NORMAL) {
                light = LIGHT_NORMAL;
            } else if (light > LIGHT_NORMAL && light <= LIGHT_50_PERCENT) {
                light = LIGHT_50_PERCENT;
            } else if (light > LIGHT_50_PERCENT
                    && light <= LIGHT_75_PERCENT) {
                light = LIGHT_75_PERCENT;
            } else {
                light = LIGHT_100_PERCENT;
            }
        } else {
            light = LIGHT_AUTO;
        }

        switch (light) {
        case LIGHT_NORMAL:
            light = LIGHT_50_PERCENT - 1;
            Toast.makeText(context, "正常亮度", Toast.LENGTH_SHORT).show();
            break;
        case LIGHT_50_PERCENT:
            light = LIGHT_75_PERCENT - 1;
            Toast.makeText(context, "較高亮度", Toast.LENGTH_SHORT).show();
            break;
        case LIGHT_75_PERCENT:
            light = LIGHT_100_PERCENT - 1;
            Toast.makeText(context, "高亮度", Toast.LENGTH_SHORT).show();
            break;
        case LIGHT_100_PERCENT:
            light = LIGHT_NORMAL - 1;
            Settings.System.putInt(cr,
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
            Toast.makeText(context, "自動亮度", Toast.LENGTH_SHORT).show();

            break;
        case LIGHT_AUTO:
            light = LIGHT_NORMAL - 1;
            Settings.System.putInt(cr,
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            Toast.makeText(context, "低亮度", Toast.LENGTH_SHORT).show();

            break;
        case LIGHT_ERR:
            light = LIGHT_NORMAL - 1;
            break;

        }

        setLight(light);
        android.provider.Settings.System.putInt(cr,
                Settings.System.SCREEN_BRIGHTNESS, light);

    } catch (SettingNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

/**
 * 設置屏幕亮度
 * @param light
 */
private void setLight(int light) {
    try {
        if (mPowerManager == null) {
            mPowerManager = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
        }

        Class<?> pmClass = Class
                .forName(mPowerManager.getClass().getName());
        // 得到PowerManager類中的成員mService(mService為PowerManagerService類型)
        Field field = pmClass.getDeclaredField("mService");
        field.setAccessible(true);
        // 實例化mService
        Object iPM = field.get(mPowerManager);
        // 得到PowerManagerService對應的Class對象
        Class<?> iPMClass = Class.forName(iPM.getClass().getName());
        /*
         * 得到PowerManagerService的函數setBacklightBrightness對應的Method對象,
         * PowerManager的函數setBacklightBrightness實現在PowerManagerService中
         */
        Method method = iPMClass.getDeclaredMethod(
                "setBacklightBrightness", int.class);
        method.setAccessible(true);
        // 調用實現PowerManagerService的setBacklightBrightness
        method.invoke(iPM, light);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

/**
 * 是否開啟飛行模式
 * @return
 */
@SuppressWarnings("deprecation")
public boolean isAirplaneModeOn() {
    return Settings.System.getInt(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}

/**
 * 飛行模式開關
 */
@SuppressWarnings("deprecation")
public void airplaneModeSwitchUtils() {
    boolean enable = isAirplaneModeOn();
    if (enable) {

        Toast.makeText(context, "關閉飛行模式", Toast.LENGTH_SHORT).show();
    } else {

        Toast.makeText(context, "開啟飛行模式", Toast.LENGTH_SHORT).show();
    }
    Settings.System.putInt(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON, !enable ? 1 : 0);
    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", !enable);
    context.sendBroadcast(intent);

}

/**
 * 是否開啟數據連接
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean isMobileDataOn() {
    Boolean isOpen = false;
    if (connManager == null) {
        connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    try {
        String methodName = "getMobileDataEnabled";
        Class cmClass = connManager.getClass();

        Method method = cmClass.getMethod(methodName, null);
        isOpen = (Boolean) method.invoke(connManager, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return isOpen;

}

/**
 * 數據連接開關
 */
@SuppressWarnings({ "unused", "unchecked" })
public void MobileDataSwitchUtils() {
    if (connManager == null) {
        connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    try {

        String methodName = "getMobileDataEnabled";
        Class cmClass = connManager.getClass();
        // Boolean isOpen = null;
        Method method = cmClass.getMethod(methodName, null);

        // isOpen = (Boolean) method.invoke(connManager, null);

        Class<?> conMgrClass = Class.forName(connManager.getClass()
                .getName());
        // 得到ConnectivityManager類的成員變量mService(ConnectivityService類型)
        Field iConMgrField = conMgrClass.getDeclaredField("mService");
        iConMgrField.setAccessible(true);
        // mService成員初始化
        Object iConMgr = iConMgrField.get(connManager);
        // 得到mService對應的Class對象
        Class<?> iConMgrClass = Class.forName(iConMgr.getClass().getName());
        /*
         * 得到mService的setMobileDataEnabled(該方法在android源碼的ConnectivityService類中實現
         * ), 該方法的參數為布爾型,所以第二個參數為Boolean.TYPE
         */
        Method setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod(
                "setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);
        /*
         * 調用ConnectivityManager的setMobileDataEnabled方法(方法是隱藏的),
         * 實際上該方法的實現是在ConnectivityService(系統服務實現類)中的
         */

        if (isMobileDataOn()) {
            Toast.makeText(context, "關閉數據連接", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "開啟數據連接", Toast.LENGTH_SHORT).show();
        }
        setMobileDataEnabledMethod.invoke(iConMgr, !isMobileDataOn());

    } catch (Exception e) {
        // TODO: handle exception
    }
}


/**
 * 情景模式切換
 */
public void silentSwitchUtils() {
    if (mAudioManager == null) {
        mAudioManager = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
    }
    int ringerMode = mAudioManager.getRingerMode();

    switch (ringerMode) {
    case AudioManager.RINGER_MODE_SILENT:
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        Toast.makeText(context, "震動模式", Toast.LENGTH_SHORT).show();
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        Toast.makeText(context, "靜音模式", Toast.LENGTH_SHORT).show();
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        Toast.makeText(context, "正常模式", Toast.LENGTH_SHORT).show();
        break;
    }

}

/**
 * 是否開啟gps
 * @return
 */
public boolean isGpsSwitchOn() {
    return Secure.isLocationProviderEnabled(context.getContentResolver(),
            LocationManager.GPS_PROVIDER);
}

/**
 * gps開關
 */
public void GpsSwitchUtils() {

    Secure.setLocationProviderEnabled(context.getContentResolver(),
            LocationManager.GPS_PROVIDER, !isGpsSwitchOn());

}

/**
 * 鎖屏
 */
public void lockScreenSwitchUtils() {
    if (mPowerManager == null) {
        mPowerManager = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
    }
    mPowerManager.goToSleep(SystemClock.uptimeMillis());
}

/**
 * 重啟
 */
public void rebootUtils() {
    if (mPowerManager == null) {
        mPowerManager = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
    }
    mPowerManager.reboot(null);

}

/**
 * 關機
 */
public void shutDownSwitchUtils() {
    Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
    intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // 彈出系統內置的對話框,選擇確定關機或取消關機
    context.startActivity(intent);


}

/**
 * 是否開啟了閃光燈
 * @return
 */
public boolean isFlashlightOn() {
    if (camera == null) {
        camera = Camera.open();
    }

    Parameters parameters = camera.getParameters();
    String flashMode = parameters.getFlashMode();

    if (flashMode.equals(Parameters.FLASH_MODE_TORCH)) {

        return true;
    } else {
        return false;
    }
}

/**
 * 閃光燈開關
 */
public void flashlightUtils() {
    if (camera == null) {
        camera = Camera.open();
    }

    Parameters parameters = camera.getParameters();
    // String flashMode = parameters.getFlashMode();

    if (isFlashlightOn()) {

        parameters.setFlashMode(Parameters.FLASH_MODE_OFF);// 關閉
        camera.setParameters(parameters);
        camera.release();
        camera = null;
        Toast.makeText(context, "關閉手電筒", Toast.LENGTH_SHORT).show();
    } else {
        parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);// 開啟
        camera.setParameters(parameters);
        Toast.makeText(context, "開啟手電筒", Toast.LENGTH_SHORT).show();
    }

}

/**
 * 閃光燈開關2
 */
public void flashUtils() {

    Camera camera = Camera.open();

    Camera.Parameters parameters = camera.getParameters();
    String flashMode = parameters.getFlashMode();
    if (flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH)) {
        camera.stopPreview();
        camera.release();
        camera = null;

    } else {

        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.autoFocus(new Camera.AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
            }
        });
        camera.startPreview();
    }
}

/**
 * 跳轉到系統設置
 */
public void systemSetUtils() {
    Intent intent = new Intent(Settings.ACTION_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}

/**
 * 跳轉到系統app管理
 */
public void systemAppsUtils() {
    Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}

/**
 * 跳轉到系統顯示設置
 */
public void systemDisplayUtils() {
    Intent intent = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}

/**
 * 跳轉到系統聲音設置
 */
public void systemSoundUtils() {
    Intent intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}

/**
 * 跳轉到系統日期設置
 */
public void systemDateUtils() {
    Intent intent = new Intent(Settings.ACTION_DATE_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}

/**
 * 跳轉到系統位置設置
 */
public void systemLocationUtils() {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}
/**
 * 跳轉到系統同步設置
 */
public void systemSyncUtils() {
    Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}
/**
 * 跳轉到系統輸入設置
 */
public void systemInputUtils() {
    Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

}



/**
 * 調大媒體音量
 */
public void setMusicAudio() {
    if (mAudioManager == null) {
        mAudioManager = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
    }

    // int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM
    // );
    // int current = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM
    // );
    mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
            AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);

}

}</pre>

 本文由用戶 yne7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!