方式一:
1.添加权限
<uses-permission android:name="android.permission.WAKE_LOCK"/>
2.获取PowerManager对象
3.通过PoverManager对象获取屏幕锁WakeLock
4.在onResume中保持wakeLock
5.在onPause方法释放wakeLock
class KeepScreenActivity extends BaseActivity{
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keep_screen);
powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "keep_Lock");
}
@Override
protected void onResume() {
super.onResume();
wakeLock.acquire();
}
@Override
protected void onPause() {
super.onPause();
wakeLock.release();
}
}
该方法是最繁琐的一种方式,因此不推介使用
方式二:
该方式不需要添加权限,直接在onCreate方法中一行代码搞定
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
方式三:
该方式是直接修改xml文件,在布局文件中添加android:keepScreenOn属性
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">
</FrameLayout>