如何让我的 android 应用程序等待 isInteractive() 方法有效地 return false?

How to make my android application wait for isInteractive() method to return false efficiently?

在我的 android 应用程序中,我每天在预定义的时间触发预定义的通知,以寻求用户的输入。我正在使用 powerManager class class 并获取唤醒锁。我能够做到这一点,但我的要求是如果用户正在使用 his/her 设备积极地做某事,我的通知 应该等待

我已经尝试过使用 powerManager class 提供的 isInteractive() 方法(下面的代码)并且 OS 有时会抛出 ANR(应用程序未响应)并且它有时会完全跳过通知。

我创建了一个新线程,只是为了让我的应用等待设备未被使用,然后调用我的通知触发部分。

    Public class myClass extends BroadcastReceiver{

    private void checkPhoneUsage(Context context, int alarmId){
        final PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        mThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try{
                                if(Build.VERSION.SDK_INT >= 20)
                                    while(pm.isInteractive())
                                        Thread.sleep(10000);
                                else if (Build.VERSION.SDK_INT < 20)
                                    while (pm.isScreenOn())
                                        Thread.sleep(10000);
                                // Call the method which fires Notification.
                                // fireNotification(alarmId);
                            }
                            catch (Exception e){
                                Log.e(Tag,"Error during thread.sleep");
                            }
                        }
                    });
       }
    }

我尝试使用 SystemClock.wait(ms) 但问题再次重复,这也失败了,因为它不应该在 UI 线程上使用。

你不应该。查看 isInteractive 的文档:

The system will send a screen on or screen off broadcast whenever the interactive state of the device changes. For historical reasons, the names of these broadcasts refer to the power state of the screen but they are actually sent in response to changes in the overall interactive state of the device, as described by this method.

改为使用广播关闭屏幕。然后在该接收器中执行您想要的任何代码。或者,如果您需要它在另一个线程上发生,让该线程等待从该接收器发送的消息。

我做了什么来绕过这个问题。

创建一个新的 Alarm Intent 以在发现设备当前处于活动状态 1 分钟后触发通知。取消之前的闹钟。

捕获警报广播并重新检查用户是否正在与设备交互。如果他没有,则继续我的实际通知,即在预定义的时间启动应用程序并设置新的警报意图。否则重复上一步或创建新的警报意图。

这样我就不会占用系统资源,并且能够实现我的 objective,即在用户未使用设备时触发通知并启动我的应用程序。