简体   繁体   English

无法使Android.os.Handler继续运行

[英]Having trouble making a Android.os.Handler continue running

So, I have a service I need to keep running in order to send an AYT to a device and report on the connection (basically whether it's up or down) at regular intervals. 因此,我有一项服务需要保持运行状态,以便将AYT发送到设备并定期报告连接(基本上是打开还是关闭)。 I have a setup right now, which works, however after about 10 or 15 minutes, it just ceases to run. 我现在有一个设置,该设置可以运行,但是大约10或15分钟后,它就停止运行了。 It's using a HandlerThread, Handler and Runnable to start the service, which does its work, then stops itself. 它使用HandlerThread,Handler和Runnable启动服务,该服务开始工作,然后自行停止。

MainActivity.java snippets: MainActivity.java代码段:

private HandlerThread hThread = new HandlerThread("MaintainConnection");
private Handler h;
private Runnable hTask = new Runnable() {
    @Override
    public void run() {
        startService(new Intent(getApplicationContext(), MaintainConnectionService.class));
        h.postDelayed(this, 2000);
    }
};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    hThread.start();
    h = new Handler(hThread.getLooper());
    /* OTHER CODE GOES HERE */
}

@Override
protected void onPause() {
    super.onPause();
    Log.v(TAG, "I am in onPause");
    h.removeCallbacks(hTask);
}

@Override
protected void onResume() {
    super.onResume();
    Log.v(TAG, "I am in onResume");
    h.post(hTask);
}

@Override
protected void onStop() {
    super.onStop();
    Log.v(TAG, "I am in onStop");
    h.removeCallbacks(hTask);
}

MaintainConnectionService.java MaintenanceConnectionService.java

public class MaintainConnectionService extends IntentService {

    public MaintainConnectionService() {
        super(MaintainConnectionService.class.getName());
    }

    private static final String TAG = "MaintainConnectionSVC";

    public static Handler UIHandler;
    static {
        UIHandler = new Handler(Looper.getMainLooper());
    }

    public static void runOnUI(Runnable runnable) {
        UIHandler.post(runnable);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            if (Comms.telnet.sendAYT(Comms.AYT_TIMEOUT)) {
                Log.d(TAG, "Sent AYT to => " + Comms.telnet.getRemoteAddress() + ":" + Comms.telnet.getRemotePort());
                runOnUI(new Runnable() {
                    public void run() {
                        ColourControlFragment.connStat.setBackgroundColor(Color.GREEN);
                        ColourControlFragment.connStatTxt.setText("Connection Established");
                    }
                });
            } else {
                runOnUI(new Runnable() {
                    public void run() {
                        ColourControlFragment.connStat.setBackgroundColor(Color.YELLOW);
                        ColourControlFragment.connStatTxt.setText("Attempting Reconnect");
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to send AYT to: " + Comms.TELNET_ADDRESS);
            runOnUI(new Runnable() {
                public void run() {
                    ColourControlFragment.connStat.setBackgroundColor(Color.RED);
                    ColourControlFragment.connStatTxt.setText("Not Connected");
                }
            });
            startService(new Intent(getApplicationContext(), EstablishConnectionService.class));
        }
        stopSelf();
    }
}

It all appears to work as expected, however as I said, after around 10 or 15 minutes, with no warning, it goes to the "Yellow" state (Attempting Reconnect) and stays there. 一切似乎都按预期工作,但是,正如我所说,大约10或15分钟后,没有任何警告,它进入“黄色”状态(尝试重新连接)并停留在那里。 If I close the app and restart it, it resumes working. 如果我关闭应用程序并重新启动它,它将恢复工作。

Any way to prevent threads being killed? 有什么方法可以防止线程被杀死吗? Any suggestions on a better way to monitor the connection? 有没有更好的方法来监视连接的建议?

I've tried plain Thread s and Timer s, to no avail. 我已经尝试了普通ThreadTimer ,但都没有用。

The Handler in your Activity should be static, otherwise you have the risk of leaking your Activity. 您的活动中的处理程序应该是静态的,否则您就有泄漏活动的风险。

Also, if you remove callbacks in onResume and onPause (doing so in both does not make sense btw), it does make sense that you no longer receiving any messages. 另外,如果您删除了onResume和onPause中的回调(btw这样做都没有意义),那么您就不会再收到任何消息了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java中是否有类似android.os.Handler的类? - Is there any class in Java similar to android.os.Handler in Android? 无法存根android.os.Handler类的post方法 - Not able to stub post method of android.os.Handler class ContentObserver中的ContentObserver(android.os.Handler)无法应用于(java.util.logging.Handler) - ContentObserver (android.os.Handler) in ContentObserver cannot be applied to (java.util.logging.Handler) 如何在 Android 应用程序中正确实现 android.os.Handler class 而不是 Timer? - How to properly implement android.os.Handler class instead of Timer in Android application? android.os.Handler类是否消除了将某些方法声明为synchronized的需要? - Does the android.os.Handler class eliminate the need to declare certain methods as synchronized? 哪个引用变量为null-尝试从null对象引用上的字段'android.os.Handler android.support.v4.ama'中读取 - which reference variable is null - Attempt to read from field 'android.os.Handler android.support.v4.a.m.a' on a null object reference 制作ActionListener时遇到麻烦 - Having trouble making a ActionListener 我无法在 android 上运行我的计算器应用程序 - I am having trouble with running my calculator app on android 在ubuntu 12.10上运行android sdk工具时遇到问题 - Having trouble running android sdk tool on ubuntu 12.10 在Android中遇到Handler问题 - Having issues with Handler in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM