如何确定手机是否处于空闲状态?

6

如何确定用户未使用手机达30分钟?

使用Jiro查看手机是否处于横向位置?

Android中是否有内置标志来识别这一点?


1
只是一个快速的问题 - 你真的需要陀螺仪/加速度计测试吗?我可以想到一些方法来检测用户是否未触摸屏幕,这样符合您的要求吗? - sudhishkr
不需要陀螺仪。我愿意听取建议。 - Elad Benda
1
检查屏幕是否开启? - martynas
4个回答

5

您应该尝试基于显示器的事件进行工作,以及最后一次启用它的时间。

ACTION_SCREEN_ONACTION_SCREEN_OFFACTION_USER_PRESENT 注册广播接收器,并正确保存时间戳。

请注意,屏幕事件也可能由诸如 WhatsApp 等应用程序触发,如果它们自动启用显示器来显示新消息。因此,您应该更多地依赖 ACTION_USER_PRESENT

以下是一些代码:

Android-Manifest.xml

<receiver android:name=".UserPresentBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.USER_PRESENT" />
  </intent-filter>
</receiver>

广播接收器

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class UserPresentBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent intent) {

        /*Sent when the user is present after 
         * device wakes up (e.g when the keyguard is gone)
         * */
        if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

        }
    }

}

代码的功劳归功于 Chathura Wijesinghe
注意:您需要一个单独的线程(最好是守护线程)来比较该时间戳和当前时间。

所以 USER_PRESENT 会使我的延时计数器归零。但是这个事件会在每次用户触摸时触发吗? - Elad Benda
此事件仅在解锁手机时调用。 - Marco de Abreu

5

监听 ACTION_SCREEN_OFF 事件来启动计时器,只有在收到 ACTION_USER_PRESENT 事件时才清除计时器,这样当屏幕被某些应用程序打开时,你不会意外地清除计时器。

使用上述方法时,您可以在启动计时器时包含以下内容。这样,当屏幕关闭时,您就考虑了自动锁定延迟。

Settings.Secure.getLong(getContentResolver(), "lock_screen_lock_after_timeout", 5000);

另外,您可以使用 KeyguardManager 在屏幕关闭后每1毫秒左右检查锁定屏幕是否已启用。

一般来说,想法是:锁屏幕--> 空闲;未锁屏幕--> 非空闲


关于上述评论,您有什么想说的吗?请注意,屏幕事件也可能由应用程序触发,例如WhatsApp,如果它们自动启用显示以显示新消息。由于这个事实,您应该坚持使用ACTION_USER_PRESENT。 - Elad Benda
@EladBenda ACTION_USER_PRESENT 检查锁屏状态。通常应用程序不能解锁您的手机,除非它本身是一个锁屏替代品,或者您已经获取了访问该操作的 root 权限。如果屏幕已解锁,则可以假定用户想要与手机进行交互,这是可以的。 - StoneBird

3

1
A lot depends on how you define "Idle". Screen off does not necessarily mean your device is idle. The most common scenario is if there is an app holding a PARTIAL_WAKE_LOCK.
One way to tackle the problem would be to listen to SCREEN_ON/OFF and ACTION_USER_PRESENT in combination with keyguard or WindowManager API to detect if user input is happening.
Though this won't work if you have a background service running, such as the uTorrent app.
Hence, if you want to use the screen on/off option, I would suggest you also check for active wakelocks ("adb shell dumpsys power" to find current active wakelocks held by the device).
There is one more way you can try, though it may be a bit tedious (depending on how accurately you want to define IDLE).

使用 Android 提供的 Systrace(LINK) 功能来跟踪 CPU 频率和其他参数,这样您就可以监视各种程度的“空闲”。

有专门的选项来跟踪 CPU 负载和 CPU 空闲事件

1.) Android 4.3 及以上版本 (API 18及以上):将 "idle" (CPU 空闲) 和 "load" (CPU 负载) 用作列表类别选项。

2.) Android 4.2 及以下版本 (API 18以下):使用 "-i, --cpu-idle" 来跟踪 CPU 空闲事件,使用 "-l, --cpu-load" 来跟踪 CPU 负载百分比 (尽管对于您的需求,CPU 空闲事件已足够)。

详细说明请查看链接,谢谢。


窗口管理器 API 以检测用户输入的活动。你有什么建议? - Elad Benda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接