Android 禁止锁屏或黑屏

转载请注明出处:http://blog.csdn.net/snailbaby_soko/article/details/56842467

场景:

通常情况我们使用的 app 都不需要用到这个功能。但一些平板的开发就很常见了,我们不希望用户不操作亦或离开平板一段时间后,平板为了省电而自动黑屏或锁屏,那么我们应该怎么做到防止应用再使用过程中禁止系统锁屏呢?

其实很简单,一个我们经常使用却忽略的权限。

 <uses-permission android:name="android.permission.WAKE_LOCK" />

 /**
     * A wake lock is a mechanism to indicate that your application needs
     * to have the device stay on.
     * <p>
     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
     * permission in an {@code <uses-permission>} element of the application's manifest.
     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
     * </p><p>
     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
     * on at the level that was requested when the wake lock was created.
     * </p><p>
     * Call {@link #release()} when you are done and don't need the lock anymore.
     * It is very important to do this as soon as possible to avoid running down the
     * device's battery excessively.
     * </p>
     */

源码介绍说,这是一个唤醒机制,就是告诉系统你的应用需要设备一直亮屏,一直开着,不要锁屏。
如果要使用这个功能,需要在配置清单 AndroidMainfest 申请权限,之后使用 acquire() 方法让设备保持亮屏,当你已经完成你的任务或者不再需要保持亮屏了使用 release() 释放。

使用方法
第一种方法:

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(); 
    }

第一种方法:

@Override  
    protected void onResume() {  
        super.onResume();  
        PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
                PowerManager.ON_AFTER_RELEASE,TAG);
        mWakeLock.acquire();  
    }  

    @Override  
    protected void onPause() {  
        super.onPause();
        if(null != mWakeLock){  
            mWakeLock.release();  
        }  
    }

随便使用一种方法都可以使你的应用不会导致设备会锁屏或黑屏。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值