Home | History | Annotate | Download | only in facade
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.googlecode.android_scripting.facade;
     18 
     19 import android.app.AlarmManager;
     20 import android.app.Service;
     21 import android.app.admin.DevicePolicyManager;
     22 import android.content.Context;
     23 import android.content.Intent;
     24 import android.media.AudioManager;
     25 import android.os.PowerManager;
     26 import android.os.SystemClock;
     27 import android.os.UserHandle;
     28 import android.provider.Settings.SettingNotFoundException;
     29 import android.view.WindowManager;
     30 
     31 import com.android.internal.widget.LockPatternUtils;
     32 
     33 import com.googlecode.android_scripting.BaseApplication;
     34 import com.googlecode.android_scripting.FutureActivityTaskExecutor;
     35 import com.googlecode.android_scripting.Log;
     36 import com.googlecode.android_scripting.future.FutureActivityTask;
     37 import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
     38 import com.googlecode.android_scripting.rpc.Rpc;
     39 import com.googlecode.android_scripting.rpc.RpcOptional;
     40 import com.googlecode.android_scripting.rpc.RpcParameter;
     41 
     42 /**
     43  * Exposes phone settings functionality.
     44  *
     45  */
     46 public class SettingsFacade extends RpcReceiver {
     47 
     48     private final Service mService;
     49     private final AndroidFacade mAndroidFacade;
     50     private final AudioManager mAudio;
     51     private final PowerManager mPower;
     52     private final AlarmManager mAlarm;
     53     private final LockPatternUtils mLockPatternUtils;
     54 
     55     /**
     56      * Creates a new SettingsFacade.
     57      *
     58      * @param service is the {@link Context} the APIs will run under
     59      */
     60     public SettingsFacade(FacadeManager manager) {
     61         super(manager);
     62         mService = manager.getService();
     63         mAndroidFacade = manager.getReceiver(AndroidFacade.class);
     64         mAudio = (AudioManager) mService.getSystemService(Context.AUDIO_SERVICE);
     65         mPower = (PowerManager) mService.getSystemService(Context.POWER_SERVICE);
     66         mAlarm = (AlarmManager) mService.getSystemService(Context.ALARM_SERVICE);
     67         mLockPatternUtils = new LockPatternUtils(mService);
     68     }
     69 
     70     @Rpc(description = "Sets the screen timeout to this number of seconds.",
     71             returns = "The original screen timeout.")
     72     public Integer setScreenTimeout(@RpcParameter(name = "value") Integer value) {
     73         Integer oldValue = getScreenTimeout();
     74         android.provider.Settings.System.putInt(mService.getContentResolver(),
     75                 android.provider.Settings.System.SCREEN_OFF_TIMEOUT, value * 1000);
     76         return oldValue;
     77     }
     78 
     79     @Rpc(description = "Returns the current screen timeout in seconds.",
     80             returns = "the current screen timeout in seconds.")
     81     public Integer getScreenTimeout() {
     82         try {
     83             return android.provider.Settings.System.getInt(mService.getContentResolver(),
     84                     android.provider.Settings.System.SCREEN_OFF_TIMEOUT) / 1000;
     85         } catch (SettingNotFoundException e) {
     86             return 0;
     87         }
     88     }
     89 
     90     @Rpc(description = "Checks the ringer silent mode setting.",
     91             returns = "True if ringer silent mode is enabled.")
     92     public Boolean checkRingerSilentMode() {
     93         return mAudio.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
     94     }
     95 
     96     @Rpc(description = "Toggles ringer silent mode on and off.",
     97             returns = "True if ringer silent mode is enabled.")
     98     public Boolean toggleRingerSilentMode(
     99             @RpcParameter(name = "enabled") @RpcOptional Boolean enabled) {
    100         if (enabled == null) {
    101             enabled = !checkRingerSilentMode();
    102         }
    103         mAudio.setRingerMode(enabled ? AudioManager.RINGER_MODE_SILENT
    104                 : AudioManager.RINGER_MODE_NORMAL);
    105         return enabled;
    106     }
    107 
    108     @Rpc(description = "Set the ringer to a specified mode")
    109     public void setRingerMode(@RpcParameter(name = "mode") Integer mode) throws Exception {
    110         if (AudioManager.isValidRingerMode(mode)) {
    111             mAudio.setRingerMode(mode);
    112         } else {
    113             throw new Exception("Ringer mode " + mode + " does not exist.");
    114         }
    115     }
    116 
    117     @Rpc(description = "Returns the current ringtone mode.",
    118             returns = "An integer representing the current ringer mode")
    119     public Integer getRingerMode() {
    120         return mAudio.getRingerMode();
    121     }
    122 
    123     @Rpc(description = "Returns the maximum ringer volume.")
    124     public int getMaxRingerVolume() {
    125         return mAudio.getStreamMaxVolume(AudioManager.STREAM_RING);
    126     }
    127 
    128     @Rpc(description = "Returns the current ringer volume.")
    129     public int getRingerVolume() {
    130         return mAudio.getStreamVolume(AudioManager.STREAM_RING);
    131     }
    132 
    133     @Rpc(description = "Sets the ringer volume.")
    134     public void setRingerVolume(@RpcParameter(name = "volume") Integer volume) {
    135         mAudio.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
    136     }
    137 
    138     @Rpc(description = "Returns the maximum media volume.")
    139     public int getMaxMediaVolume() {
    140         return mAudio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    141     }
    142 
    143     @Rpc(description = "Returns the current media volume.")
    144     public int getMediaVolume() {
    145         return mAudio.getStreamVolume(AudioManager.STREAM_MUSIC);
    146     }
    147 
    148     @Rpc(description = "Sets the media volume.")
    149     public void setMediaVolume(@RpcParameter(name = "volume") Integer volume) {
    150         mAudio.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
    151     }
    152 
    153     /**
    154     * Sets the voice call volume.
    155     * @param volume the volume number to be set for voice call.
    156     */
    157     @Rpc(description = "Sets the voice call volume.")
    158     public void setVoiceCallVolume(@RpcParameter(name = "volume") Integer volume) {
    159         mAudio.setStreamVolume(AudioManager.STREAM_VOICE_CALL, volume, 0);
    160     }
    161 
    162     /**
    163     * Sets the alarm volume.
    164     * @param volume the volume number to be set for alarm.
    165     */
    166     @Rpc(description = "Sets the alarm volume.")
    167     public void setAlarmVolume(@RpcParameter(name = "volume") Integer volume) {
    168         mAudio.setStreamVolume(AudioManager.STREAM_ALARM, volume, 0);
    169     }
    170 
    171     @Rpc(description = "Returns the screen backlight brightness.",
    172             returns = "the current screen brightness between 0 and 255")
    173     public Integer getScreenBrightness() {
    174         try {
    175             return android.provider.Settings.System.getInt(mService.getContentResolver(),
    176                     android.provider.Settings.System.SCREEN_BRIGHTNESS);
    177         } catch (SettingNotFoundException e) {
    178             return 0;
    179         }
    180     }
    181 
    182     @Rpc(description = "return the system time since boot in nanoseconds")
    183     public long getSystemElapsedRealtimeNanos() {
    184         return SystemClock.elapsedRealtimeNanos();
    185     }
    186 
    187     @Rpc(description = "Sets the the screen backlight brightness.",
    188             returns = "the original screen brightness.")
    189     public Integer setScreenBrightness(
    190             @RpcParameter(name = "value", description = "brightness value between 0 and 255") Integer value) {
    191         if (value < 0) {
    192             value = 0;
    193         } else if (value > 255) {
    194             value = 255;
    195         }
    196         final int brightness = value;
    197         Integer oldValue = getScreenBrightness();
    198         android.provider.Settings.System.putInt(mService.getContentResolver(),
    199                 android.provider.Settings.System.SCREEN_BRIGHTNESS, brightness);
    200 
    201         FutureActivityTask<Object> task = new FutureActivityTask<Object>() {
    202             @Override
    203             public void onCreate() {
    204                 super.onCreate();
    205                 WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
    206                 lp.screenBrightness = brightness * 1.0f / 255;
    207                 getActivity().getWindow().setAttributes(lp);
    208                 setResult(null);
    209                 finish();
    210             }
    211         };
    212 
    213         FutureActivityTaskExecutor taskExecutor =
    214                 ((BaseApplication) mService.getApplication()).getTaskExecutor();
    215         taskExecutor.execute(task);
    216 
    217         return oldValue;
    218     }
    219 
    220     @Rpc(description = "Returns true if the device is in an interactive state.")
    221     public Boolean isDeviceInteractive() throws Exception {
    222         return mPower.isInteractive();
    223     }
    224 
    225     @Rpc(description = "Issues a request to put the device to sleep after a delay.")
    226     public void goToSleep(Integer delay) {
    227         mPower.goToSleep(SystemClock.uptimeMillis() + delay);
    228     }
    229 
    230     @Rpc(description = "Issues a request to put the device to sleep right away.")
    231     public void goToSleepNow() {
    232         mPower.goToSleep(SystemClock.uptimeMillis());
    233     }
    234 
    235     @Rpc(description = "Issues a request to wake the device up right away.")
    236     public void wakeUpNow() {
    237         mPower.wakeUp(SystemClock.uptimeMillis());
    238     }
    239 
    240     @Rpc(description = "Get Up time of device.",
    241             returns = "Long value of device up time in milliseconds.")
    242     public long getDeviceUpTime() throws Exception {
    243         return SystemClock.elapsedRealtime();
    244     }
    245 
    246     @Rpc(description = "Set a string password to the device.")
    247     public void setDevicePassword(@RpcParameter(name = "password") String password) {
    248         // mLockPatternUtils.setLockPatternEnabled(true, UserHandle.myUserId());
    249         mLockPatternUtils.setLockScreenDisabled(false, UserHandle.myUserId());
    250         mLockPatternUtils.setCredentialRequiredToDecrypt(true);
    251         mLockPatternUtils.saveLockPassword(password, null,
    252                 DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, UserHandle.myUserId());
    253     }
    254 
    255     @Rpc(description = "Disable screen lock password on the device.")
    256     public void disableDevicePassword() {
    257         mLockPatternUtils.clearEncryptionPassword();
    258         // mLockPatternUtils.setLockPatternEnabled(false, UserHandle.myUserId());
    259         mLockPatternUtils.setLockScreenDisabled(true, UserHandle.myUserId());
    260         mLockPatternUtils.setCredentialRequiredToDecrypt(false);
    261         mLockPatternUtils.clearEncryptionPassword();
    262         mLockPatternUtils.clearLock(null, UserHandle.myUserId());
    263         mLockPatternUtils.setLockScreenDisabled(true, UserHandle.myUserId());
    264     }
    265 
    266     @Rpc(description = "Set the system time in epoch.")
    267     public void setTime(Long currentTime) {
    268         mAlarm.setTime(currentTime);
    269     }
    270 
    271     @Rpc(description = "Set the system time zone.")
    272     public void setTimeZone(@RpcParameter(name = "timeZone") String timeZone) {
    273         mAlarm.setTimeZone(timeZone);
    274     }
    275 
    276     @Rpc(description = "Show Home Screen")
    277     public void showHomeScreen() {
    278         Intent intent = new Intent(Intent.ACTION_MAIN);
    279         intent.addCategory(Intent.CATEGORY_HOME);
    280         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    281         try {
    282             mAndroidFacade.startActivityIntent(intent, false);
    283         } catch (RuntimeException e) {
    284             Log.d("showHomeScreen RuntimeException" + e);
    285         } catch (Exception e){
    286             Log.d("showHomeScreen exception" + e);
    287         }
    288     }
    289 
    290     @Override
    291     public void shutdown() {
    292         // Nothing to do yet.
    293     }
    294 }
    295