您好,登錄后才能下訂單哦!
打開和關閉手機屏幕方法:
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" />
通過以上步驟,就可以實現開啟屏幕了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。