android - 为什么手机的充电状态会影响我的应用程序的行为

标签 android postdelayed

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

但是我注意到,当手机充电时(AC 或 USB),它工作正常,但如果手机断开连接,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发布解决方案如下:

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.

希望我有所帮助:)

关于android - 为什么手机的充电状态会影响我的应用程序的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32220504/

相关文章:

Android Recyclerview项目Textview不会显示在某些项目中

Android 只显示一个 admob 广告

android - 将计时器与 ProgressDialog 一起使用

android - 为什么 Handler 没有按预期触发警报?

android - 如何延迟执行android

android - Android VideoView播放4秒后如何暂停

安卓 NoSuchAlgorithmException : "SSLContext SSL implementation not found"

android - 从 Android 应用程序向 Google 日历添加事件

android - 强制显示默认的 Android 软键盘

java - 为什么这个 postDelayed 不会永远运行?