为什么 phone 的充电状态会影响我的应用的行为

Why charging state of the phone affects my app's behavior

我有一个 Runnable r,由 handler.postDelayed(60*1000) 每分钟定期触发一次。我在真实设备上测试我的代码。

但是我注意到,当 phone 正在充电(AC 或 USB)时,它工作正常,但是如果 phone 断开连接,Runnable r 只会 运行 每 20 分钟一次,甚至更糟,几个小时。感谢您的帮助!

代码如下:

private final Runnable listen_to_server = new Runnable(){
    public void run(){
        new Thread() {
            public void run() {
                try {

                    handler.sendMessage(handler.obtainMessage(PING_SERVER,"listen"));
                    synchronized (listen) {
                        listen.wait();
                    }
                    handler.postDelayed(listen_to_server, 50000);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }
};

在处理程序中:

    handler=new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case PING_SERVER:
                    String type = (String) msg.obj;
                    add_log("ping server"); // print to screen and Log.d
                    ...
                    ...
            }
        }
    }

关于 this link 我认为问题可能是,正如他们所说:

Android is not a real-time operating system. All postDelayed() guarantees is that it will be at least the number of milliseconds specified. Beyond that will be dependent primarily on what the main application thread is doing (if you are tying it up, it cannot process the Runnable), and secondarily on what else is going on the device (services run with background priority and therefore get less CPU time than does the foreground).

如何解决这个问题?在 this post 中,解决方案如下:

You'll probably have better luck using the AlarmManager for such a long delay. Handler is best for ticks and timeouts while your app is in the foreground.

所以尝试实现一个 AlarmManager 查看 the doc.

希望我能帮到你 :)