首页 > 代码库 > android打开关闭屏幕

android打开关闭屏幕


打开和关闭手机屏幕方法:


1.关闭屏幕

//设备管理者

private DevicePolicyManager mDevicePolicyManager;

//关屏组件

private ComponentName mCompName;


onCreate()

{

mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

// 申请权限

mCompName = new ComponentName(this, YNAdminReceiver.class);

}


//点击按钮关闭屏幕

public void onScreenOff(View view) {

// 判断该组件是否有系统管理员的权限

if (!mDevicePolicyManager.isAdminActive(mCompName)) {//这一句一定要有...

Intent intent = new Intent();

//指定动作

intent.setAction(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

//指定给那个组件授权

intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mCompName);

startActivity(intent);

} else {

//立即关闭屏幕

mDevicePolicyManager.lockNow();

//                    devicePolicyManager.resetPassword("123321", 0);

Log.i(TAG, "具有权限,将进行锁屏....");

Log.i(TAG, "going to shutdown screen");

}

}


其中,组件mCompName是一个DeviceAdminReceiver:

package com.yn.receivers;

public class YNAdminReceiver extends DeviceAdminReceiver {

}

以上就是关屏的代码部分,剩下还需配置:

//res/xml/yndeviceadmin.xml

<?xml version="1.0" encoding="utf-8"?>

<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >

<uses-policies>

<force-lock />

</uses-policies>

</device-admin>


//AndroidMainfest.xml

<!-- 配置权限 -->

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

<!-- 声明关屏组件 -->

<receiver android:name="com.yn.receivers.YNAdminReceiver" >

<meta-data android:name="android.app.device_admin"

<!-- 指定组件配置 -->

android:resource="@xml/yndeviceadmin/>

<intent-filter >

<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>

</intent-filter>

</receiver>

通过以上配置,就可以实现关屏了。



2.打开屏幕(打开屏幕,只需一个wakelock即可)

private PowerManager mPowerManager;

private PowerManager.WakeLock mScreenLock;


onCreate()

{

mPowerManager = ((PowerManager) getSystemService(POWER_SERVICE));

mScreenLock = mPowerManager.newWakeLock(

PowerManager.ACQUIRE_CAUSES_WAKEUP //该flag使能屏幕关闭时,也能点亮屏幕(通常的wakelock只能维持屏幕处于一直开启状态,如果灭屏时,是不会自动点亮的)

| PowerManager.SCREEN_DIM_WAKE_LOCK

| PowerManager.ON_AFTER_RELEASE, "screenOnWakeLock");

}


//点击按钮,5s后获取锁(如果此时屏幕处于关闭状态,5s后获取锁时,会点亮屏幕)

public void onScreenOn(View View) {

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

//isHeld(),判断是否获取锁,false未获取锁

if (!mScreenLock.isHeld()) {

mScreenLock.acquire();

Toast.makeText(MainActivity.this, "acquire", Toast.LENGTH_SHORT).show();

} else {

mScreenLock.release();

Toast.makeText(MainActivity.this, "release", Toast.LENGTH_SHORT).show();


}

}

}, 5000);

}


最后,还需要在AndroidManifest.xml中配置权限

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


通过以上步骤,就可以实现开启屏幕了。


本文出自 “whatever957” 博客,请务必保留此出处http://whatever957.blog.51cto.com/6835003/1864346

android打开关闭屏幕