Android学习之路------自定义屏保程序判断当前系统有视频正在播放

引言

最近在一个项目中,客户需要开发一个屏保程序,屏保程序是循环播放一段时间,要求是需要判断当前系统是否有媒体在播放,比如video或者音乐在播放都不能执行我们的屏保程序

解决方法

那么如何判断当前系统是否有视频在播放呢。

if(audio==null){
    audio = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
}
if(audio.isMusicActive()){
    //代表当前有视频在播放
}

上述代码在一般情况下是可以准确判断的,但是在一些特殊情况比如网络环境不好时,视频正在缓冲,导致

audio.isMusicActive()

返回false,当时我验证了系统自带的屏保程序,发现视频缓冲时,原生的屏保并不会执行,因此我猜测系统可能判断了什么变量,后来我感觉这个可能跟休眠时差不多的,因此我们可能判断wakelock来决定是否要执行我们的屏保程序,在应用层是无法得到wakelock的状态的,但是我们可以运行一条指令

dumpsys power

运行指令之后 通过读取其中的wakelock size就能判断当前系统中是否有程序申请了wake lock,如果有并且应用程序没释放这个锁,那我们就不开启我们的屏保程序,代码如下:

private boolean getTheWakeLock(){
        try{
            ArrayList command = new ArrayList();
            command.add("dumpsys");
            command.add("power");
            Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = null;
            while(true){
                str = reader.readLine();
                if(str==null){
                    continue;
                }

                if(str.contains("Wake Locks:")){
                    String[] wakelock = str.split("=");

                    if(Integer.parseInt(wakelock[1]) > 0){
                        return true;//当前有系统锁
                    }
                    break;
                }
            }



        }catch(Exception e){

        }
        return false;//当前无系统锁
    }

下面我贴一段输入dumpsys power之后返回的数据。相信大家就明白了

root@m201C:/ # dumpsys power
POWER MANAGER (dumpsys power)

Power Manager State:
  mDirty=0x0
  mWakefulness=Awake
  mIsPowered=true
  mPlugType=0
  mBatteryLevel=0
  mBatteryLevelWhenDreamStarted=0
  mDockState=0
  mStayOn=false
  mProximityPositive=false
  mBootCompleted=true
  mSystemReady=true
  mWakeLockSummary=0x0
  mUserActivitySummary=0x1
  mRequestWaitForNegativeProximity=false
  mSandmanScheduled=false
  mLastWakeTime=0 (133656 ms ago)
  mLastSleepTime=0 (133656 ms ago)
  mSendWakeUpFinishedNotificationWhenReady=false
  mSendGoToSleepFinishedNotificationWhenReady=false
  mLastUserActivityTime=20754 (112902 ms ago)
  mLastUserActivityTimeNoChangeLights=0 (133656 ms ago)
  mDisplayReady=true
  mHoldingWakeLockSuspendBlocker=false
  mHoldingDisplaySuspendBlocker=true

Settings and Configuration:
  mWakeUpWhenPluggedOrUnpluggedConfig=false
  mSuspendWhenScreenOffDueToProximityConfig=false
  mDreamsSupportedConfig=true
  mDreamsEnabledByDefaultConfig=true
  mDreamsActivatedOnSleepByDefaultConfig=true
  mDreamsActivatedOnDockByDefaultConfig=true
  mDreamsEnabledSetting=true
  mDreamsActivateOnSleepSetting=true
  mDreamsActivateOnDockSetting=true
  mScreenOffTimeoutSetting=2147483647
  mMaximumScreenOffTimeoutFromDeviceAdmin=2147483647 (enforced=false)
  mStayOnWhilePluggedInSetting=0
  mScreenBrightnessSetting=102
  mScreenAutoBrightnessAdjustmentSetting=0.0
  mScreenBrightnessModeSetting=0
  mScreenBrightnessOverrideFromWindowManager=-1
  mUserActivityTimeoutOverrideFromWindowManager=-1
  mTemporaryScreenBrightnessSettingOverride=-1
  mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=NaN
  mScreenBrightnessSettingMinimum=20
  mScreenBrightnessSettingMaximum=255
  mScreenBrightnessSettingDefault=102

Screen off timeout: 2147483647 ms
Screen dim duration: 7000 ms

Wake Locks: size=0

Suspend Blockers: size=4
  PowerManagerService.WakeLocks: ref count=0
  PowerManagerService.Display: ref count=1
  PowerManagerService.Broadcasts: ref count=0
  PowerManagerService.WirelessChargerDetector: ref count=0

Screen On Blocker: held=false, mNestCount=0

Display Blanker: blanked=false

Display Controller Locked State:
  mDisplayReadyLocked=true
  mPendingRequestLocked=screenState=2, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=0.0, useAutoBrightness=false, blockScreenOn=false
  mPendingRequestChangedLocked=false
  mPendingWaitForNegativeProximityLocked=false
  mPendingUpdatePowerStateLocked=false

Display Controller Configuration:
  mScreenBrightnessDimConfig=10
  mScreenBrightnessRangeMinimum=10
  mScreenBrightnessRangeMaximum=255
  mUseSoftwareAutoBrightnessConfig=false
  mScreenAutoBrightnessSpline=null
  mLightSensorWarmUpTimeConfig=0

Display Controller Thread State:
  mPowerRequest=screenState=2, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=0.0, useAutoBrightness=false, blockScreenOn=false
  mWaitingForNegativeProximity=false
  mProximitySensor=null
  mProximitySensorEnabled=false
  mProximityThreshold=0.0
  mProximity=Unknown
  mPendingProximity=Unknown
  mPendingProximityDebounceTime=-1 (133660 ms ago)
  mScreenOffBecauseOfProximity=false
  mLightSensor=null
  mLightSensorEnabled=false
  mLightSensorEnableTime=0 (133659 ms ago)
  mAmbientLux=0.0
  mAmbientLuxValid=false
  mLastObservedLux=0.0
  mLastObservedLuxTime=0 (133659 ms ago)
  mRecentLightSamples=0
  mRecentShortTermAverageLux=0.0
  mRecentLongTermAverageLux=0.0
  mDebounceLuxDirection=0
  mDebounceLuxTime=0 (133659 ms ago)
  mScreenAutoBrightness=-1
  mUsingScreenAutoBrightness=false
  mLastScreenAutoBrightnessGamma=1.0
  mTwilight.getCurrentState()=null
  mElectronBeamOnAnimator.isStarted()=false
  mElectronBeamOffAnimator.isStarted()=false

Display Power State:
  mScreenOn=true
  mScreenBrightness=102
  mScreenReady=true
  mScreenUpdatePending=false
  mElectronBeamPrepared=false
  mElectronBeamLevel=1.0
  mElectronBeamReady=true
  mElectronBeamDrawPending=false

Photonic Modulator State:
  mPendingOn=true
  mPendingBacklight=102
  mActualOn=true
  mActualBacklight=102
  mChangeInProgress=false

Electron Beam State:
  mPrepared=false
  mMode=0
  mDisplayLayerStack=0
  mDisplayWidth=0
  mDisplayHeight=0
  mSurfaceVisible=false
  mSurfaceAlpha=0.0

Wireless Charger Detector State:
  mGravitySensor=null
  mPoweredWirelessly=false
  mAtRest=false
  mRestX=0.0, mRestY=0.0, mRestZ=0.0
  mDetectionInProgress=false
  mDetectionStartTime=0 (never)
  mMustUpdateRestPosition=false
  mTotalSamples=0
  mMovingSamples=0
  mFirstSampleX=0.0, mFirstSampleY=0.0, mFirstSampleZ=0.0
  mLastSampleX=0.0, mLastSampleY=0.0, mLastSampleZ=0.0

上述输出中有一句打印:


Wake Locks: size=0

表明当前系统中没有应用程序申请wake lock

结语

现在这种处理方式只是暂时解决了客户需求,但是我觉得应该有更好的办法,如果大家知道请不啬赐教

你可能感兴趣的:(Android学习,android,屏保,wakelock)