如何prevent自动锁屏Android上由code?prevent、Android、code

2023-09-05 02:39:56 作者:别重逢

在我的应用还有很长的加载过程中,如果设备戴上屏幕锁,我的进程将停止的某些原因。

In my app there is a long loading process, and if the devices puts on the screen lock, my process stops for some reason.

如何prevent设备从自动锁屏?

How can i prevent the device from automatic screen lock?

推荐答案

您必须声明此使用,权限AndroidManifest:

you have to declare this uses-permission on AndroidManifest:

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

而在你的code活动:

And in your code Activity:

PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
wakeLock.acquire();

不过,别忘了释放此锁,当你的应用程序被暂停或摧毁这样做:

Just remember to release this lock when your application is paused or destroyed by doing this:

wakeLock.release();

通常情况下,它的建议致电获得方式的 onResume()您的活动,并在发布法里面的的onPause ()。这样,我们保证我们的应用程序仍处于被暂停的情况下表现良好或恢复。

Usually, it's suggested to call the acquire method inside the onResume() of your activity and the release method in onPause(). This way we guarantee that our application still performs well in the case of being paused or resumed.