您好,登錄后才能下訂單哦!
打開和關(guān)閉手機(jī)屏幕方法:
1.關(guān)閉屏幕
//設(shè)備管理者
private DevicePolicyManager mDevicePolicyManager;
//關(guān)屏組件
private ComponentName mCompName;
onCreate()
{
mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// 申請權(quán)限
mCompName = new ComponentName(this, YNAdminReceiver.class);
}
//點(diǎn)擊按鈕關(guān)閉屏幕
public void onScreenOff(View view) {
// 判斷該組件是否有系統(tǒng)管理員的權(quán)限
if (!mDevicePolicyManager.isAdminActive(mCompName)) {//這一句一定要有...
Intent intent = new Intent();
//指定動(dòng)作
intent.setAction(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//指定給那個(gè)組件授權(quán)
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mCompName);
startActivity(intent);
} else {
//立即關(guān)閉屏幕
mDevicePolicyManager.lockNow();
// devicePolicyManager.resetPassword("123321", 0);
Log.i(TAG, "具有權(quán)限,將進(jìn)行鎖屏....");
Log.i(TAG, "going to shutdown screen");
}
}
其中,組件mCompName是一個(gè)DeviceAdminReceiver:
package com.yn.receivers;
public class YNAdminReceiver extends DeviceAdminReceiver {
}
以上就是關(guān)屏的代碼部分,剩下還需配置:
//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
<!-- 配置權(quán)限 -->
<uses-permission android:name="android.permission.USES_POLICY_FORCE_LOCK" />
<!-- 聲明關(guān)屏組件 -->
<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>
通過以上配置,就可以實(shí)現(xiàn)關(guān)屏了。
2.打開屏幕(打開屏幕,只需一個(gè)wakelock即可)
private PowerManager mPowerManager;
private PowerManager.WakeLock mScreenLock;
onCreate()
{
mPowerManager = ((PowerManager) getSystemService(POWER_SERVICE));
mScreenLock = mPowerManager.newWakeLock(
PowerManager.ACQUIRE_CAUSES_WAKEUP //該flag使能屏幕關(guān)閉時(shí),也能點(diǎn)亮屏幕(通常的wakelock只能維持屏幕處于一直開啟狀態(tài),如果滅屏?xí)r,是不會(huì)自動(dòng)點(diǎn)亮的)
| PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, "screenOnWakeLock");
}
//點(diǎn)擊按鈕,5s后獲取鎖(如果此時(shí)屏幕處于關(guān)閉狀態(tài),5s后獲取鎖時(shí),會(huì)點(diǎn)亮屏幕)
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中配置權(quán)限
<uses-permission android:name="android.permission.WAKE_LOCK" />
通過以上步驟,就可以實(shí)現(xiàn)開啟屏幕了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。