我想在后台处理 Android 应用程序工作。我读过我必须为此使用服务。在这个应用程序中,我需要知道屏幕何时被锁定以及何时再次解锁。每次发生这种情况,我都必须采取一些措施。
对于活动,我已经看到我们为此设置了 onPause 和 onRestart,但我需要知道屏幕何时关闭以及何时在服务中打开。如何从服务内部检索此信息。
我想在后台处理 Android 应用程序工作。我读过我必须为此使用服务。在这个应用程序中,我需要知道屏幕何时被锁定以及何时再次解锁。每次发生这种情况,我都必须采取一些措施。
对于活动,我已经看到我们为此设置了 onPause 和 onRestart,但我需要知道屏幕何时关闭以及何时在服务中打开。如何从服务内部检索此信息。
打开/关闭屏幕会产生系统事件。您必须收听这些广播并捕获它们。将此添加到您的清单中:
<receiver android:name=".ScreenLockBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>
然后注册一个广播接收器以在您的服务中捕获它。
public class ScreenLockBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
// do stuff
}
}
}
你可以用这个
KeyguardManager keyguardManager = (KeyguardManager)
context.getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.inKeyguardRestrictedInputMode()) {
//it is locked
} else {
//it is not locked
}
希望这可以帮助。
在清单中的接收者标签中使用此操作
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
我想在后台创建 android 应用程序工作,我读过我必须使用这些服务。
是的,可能您必须使用服务来检查屏幕是否仍然亮着或熄灭。例如在onCreate
你的Services
班级。
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver broadcast = new MyBroadcastReciverClass(); //or
registerReceiver(broadcast , intentFilter );
实际上:
Intent.ACTION_SCREEN_OFF
或者
Intent.ACTION_SCREEN_ON
有两件主要的事情也必须进入你的BroadcastReceiver
。例如在你的onReceive
方法中:
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// CODE HERE FOR SCREEN OFF
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// CODE HERE FOR SCREEN ON
}
有关更详细的解释,请查看本文:https ://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/