禁止屏幕熄灭

我们有的时候在写的一些程序,需要让该应用程序运行的时候,屏幕一直亮着:

没几行代码,直接上代码,代码如下:

 1 import android.app.Activity;
 2 import android.content.Context;
 3 import android.os.Bundle;
 4 import android.os.PowerManager;
 5 import android.os.PowerManager.WakeLock;
 6 
 7 public class MainActivity extends Activity {
 8 
 9     private PowerManager mPowerManager = null;
10     private WakeLock mWakeLock = null;
11 
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_main);
16         this.mPowerManager = (PowerManager) this
17                 .getSystemService(Context.POWER_SERVICE);
18         this.mWakeLock = this.mPowerManager.newWakeLock(
19                 PowerManager.FULL_WAKE_LOCK, "zhj");
20     }
21 
22     @Override
23     protected void onResume() {
24         // TODO Auto-generated method stub
25         super.onResume();
26         this.mWakeLock.acquire();
27     }
28 
29     @Override
30     protected void onPause() {
31         // TODO Auto-generated method stub
32         super.onPause();
33         this.mWakeLock.release();// 如果不执行这行代码,屏幕讲一直处于常亮状态
34     }
35 
36 }

最后注意还需要申请权限:

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

=

你可能感兴趣的:(禁止屏幕熄灭)