繁星coding
对我来说,这些方法不起作用。所以我使用其他场景(不是微不足道)来关闭我的屏幕。Android有2个标志,负责清醒:显示 - >屏幕TimeOut应用程序 - >开发 - > 充电时保持清醒复选框。我使用了以下流程:首先保存您之前的配置,例如屏幕超时为1分钟,并 在充电时保持清醒状态。之后,我取消选中充电时保持清醒并将屏幕超时设置为最短时间。我注册广播接收器服务从屏幕关闭的Android获取事件。当我关闭屏幕上的事件时,我将先前的配置设置为默认值:屏幕超时为1分钟并且 在检查充电时保持清醒状态。取消注册接收器15秒后 设备睡觉这是代码片段:广播接收器import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;/** * Catch Screen On/Off * */public class BroadcastReceiverScreenListener extends BroadcastReceiver{private BroadCastListenerCallBackItf mBroadCastListenerCallBack = null;public BroadcastReceiverScreenListener( BroadCastListenerCallBackItf broadCastListenerCallBack) { this.mBroadCastListenerCallBack = broadCastListenerCallBack;}@Overridepublic void onReceive(Context arg0, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { mBroadCastListenerCallBack.broadCastListenerCallBack__ScreenOff_onResponse(); } }}用作回调的接口public interface BroadCastListenerCallBackItf { public void broadCastListenerCallBack__ScreenOff_onResponse();}主类2种方法:....AndroidSynchronize mSync = new AndroidSynchronize();....public void turnScreenOff(int wait){ IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadCastListenerCallBackItf broadCastListenerCallBack = this; BroadcastReceiver mReceiver = new BroadcastReceiverScreenListener(broadCastListenerCallBack); m_context.registerReceiver(mReceiver, filter); //set Development --> disable STAY_ON_WHILE_PLUGGED_IN Settings.System.putInt( m_context.getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0 ); // take current screen off time int defTimeOut = Settings.System.getInt(m_context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 3000); // set 15 sec Settings.System.putInt(m_context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000); // wait 200 sec till get response from BroadcastReceiver on Screen Off mSync.doWait(wait*1000); // set previous settings Settings.System.putInt(m_context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut); // switch back previous state Settings.System.putInt( m_context.getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_USB); m_context.unregisterReceiver(mReceiver);}public void broadCastListenerCallBack__ScreenOff_onResponse() { mSync.doNotify();}....AndroidSynchronize类public class AndroidSynchronize { public void doWait(long l){ synchronized(this){ try { this.wait(l); } catch(InterruptedException e) { } } } public void doNotify() { synchronized(this) { this.notify(); } } public void doWait() { synchronized(this){ try { this.wait(); } catch(InterruptedException e) { } } }}[编辑]您需要注册权限:android.permission.WRITE_SETTINGS