Android点亮屏幕功能

应用在涉及音视频播放功能时可能需要点亮屏幕,此文把点亮屏幕相关工具类和使用类的代码贴出来,若有问题欢迎指正!

工具类:WakeLockUtil,相关代码如下:

public class WakeLockUtil {

    /**
     * 点亮屏幕
     *
     * @param timeout The timeout after which to release the wake lock, in milliseconds.
     */
    @Nullable
    public static PowerManager.WakeLock acquireWakeLock(@NonNull Context context, long timeout) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return null;
        PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                        PowerManager.FULL_WAKE_LOCK |
                        PowerManager.ON_AFTER_RELEASE,
                context.getClass().getName());
        wakeLock.acquire(timeout);
        return wakeLock;
    }

    public static void release(@Nullable PowerManager.WakeLock wakeLock) {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }
    }
}

使用类:WakeLockActivity,相关代码如下:

public class WakeLockActivity extends AppCompatActivity {
    private PowerManager.WakeLock mWakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //点亮屏幕2分钟,2分钟后此方法会自动释放PowerManager.WakeLock
        mWakeLock = WakeLockUtil.acquireWakeLock(this, 2 * 60 * 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WakeLockUtil.release(mWakeLock);
    }
}

相关权限如下:

 

你可能感兴趣的:(android开发代码,android,点亮屏幕,唤醒屏幕,WakeLockUtil)