PowerManger WakeLock 解析

    xiaoxiao2021-03-25  149

    PowerManager.WakeLock有加锁和解锁两种状态,加锁的方式有两种,一种是永久的锁住,这样的锁除非显式的放开,是不会解锁的,所以这种锁用起来要非常的小心。第二种锁是超时锁,这种锁会在锁住后一段时间解锁。

    永久锁

    public void acquire() { synchronized (mToken) { acquireLocked(); } }

    超时锁

    public void acquire(long timeout) { synchronized (mToken) { acquireLocked(); mHandler.postDelayed(mReleaser, timeout); } }

    当时间到达超时限定以后,执行release(),释放锁

    private final Runnable mReleaser = new Runnable() { public void run() { release(); } };

    在创建了PowerManager.WakeLock后,有两种机制,第一种是不计数锁机制,另一种是计数锁机制。可以通过setReferenceCounted(boolean value)来指定,一般默认为计数机制。mRefCounted 为 true 为计数锁,false为非计数锁

    /** * Sets whether this WakeLock is reference counted. * <p> * Wake locks are reference counted by default. If a wake lock is * reference counted, then each call to {@link #acquire()} must be * balanced by an equal number of calls to {@link #release()}. If a wake * lock is not reference counted, then one call to {@link #release()} is * sufficient to undo the effect of all previous calls to {@link #acquire()}. * </p> * * @param value True to make the wake lock reference counted, false to * make the wake lock non-reference counted. */ public void setReferenceCounted(boolean value) { synchronized (mToken) { mRefCounted = value; } }

    转载请注明原文地址: https://ju.6miu.com/read-16089.html

    最新回复(0)