0

我想在后台处理 Android 应用程序工作。我读过我必须为此使用服务。在这个应用程序中,我需要知道屏幕何时被锁定以及何时再次解锁。每次发生这种情况,我都必须采取一些措施。

对于活动,我已经看到我们为此设置了 onPause 和 onRestart,但我需要知道屏幕何时关闭以及何时在服务中打开。如何从服务内部检索此信息。

4

4 回答 4

1

打开/关闭屏幕会产生系统事件。您必须收听这些广播并捕获它们。将此添加到您的清单中:

<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
        }
    }
}
于 2017-06-06T10:46:57.283 回答
0

你可以用这个

KeyguardManager keyguardManager = (KeyguardManager) 
context.getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.inKeyguardRestrictedInputMode()) {
  //it is locked
  } else {
  //it is not locked
}

希望这可以帮助。

于 2017-06-06T10:56:08.923 回答
0

在清单中的接收者标签中使用此操作

 <action android:name="android.intent.action.SCREEN_ON" />
 <action android:name="android.intent.action.SCREEN_OFF" />
于 2017-06-06T10:56:34.033 回答
0

我想在后台创建 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/

于 2017-06-06T10:59:26.060 回答