android屏幕常亮保持

相关的变量:

    PowerManager powerManager = null;
    WakeLock wakeLock = null;
初始化:

    powerManager = (PowerManager) this
                .getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");

开启屏幕常亮:

            wakeLock.setReferenceCounted(false);
            wakeLock.acquire();

关闭你的程序设置的屏幕常亮:

            wakeLock.release();

注意的地方:我在实际的调试过程中,没有设置wakeLock.setReferenceCounted(false);这个,报错为:java.lang.RuntimeException: WakeLock under-locked

                 阅读源码:

         acquire()函数如下:

                        public void acquire()
        {
            synchronized (mToken) {
                if (!mRefCounted || mCount++ == 0) {
                    try {
                        mService.acquireWakeLock(mFlags, mToken, mTag);
                    } catch (RemoteException e) {
                    }
                    mHeld = true;
                }
            }
        }

  release()函数如下:

               public void release()
        {
            release(0);
        }

       public void release(int flags)
        {
            synchronized (mToken) {
                if (!mRefCounted || --mCount == 0) {
                    try {
                        mService.releaseWakeLock(mToken, flags);
                    } catch (RemoteException e) {
                    }
                    mHeld = false;
                }
                if (mCount < 0) {
                    throw new RuntimeException("WakeLock under-locked " + mTag);
                }
            }
        }

报错就抱在release(int flags)中,mCount为负数了,抛除了异常

我们再看下:setReferenceCounted(boolean flags);

      public void setReferenceCounted(boolean value)
        {
            mRefCounted = value;
        }

  这个函数的作用是是不是需要计算锁的数量,设置为false时,在release()的时候,不管你acquire()了多少回,可以releaseWakeLock掉

 网上看到很多   acquire()后直接就调用release(),误导大家

 这个是我自己的一些看法,欢迎探讨

 

                  

posted @ 2012-03-07 10:37  tgwtt  阅读(7778)  评论(0编辑  收藏  举报