简体   繁体   English

Android线程未在后台运行

[英]Android thread is not running in the background

My Thread on Android is not running precisely. Android上的“我的线程”运行不正确。 I'm starting that from a Service, but somewhy it's not running correctly. 我从服务开始,但是为什么它不能正常运行。

Service: 服务:

ServiceHelper sh = new ServiceHelper();
new Thread(sh).start();

public class ServiceHelper implements Runnable {
    public void run() {
        while(true) {
            Log.d(LOG_TAG, "run");
            //1.) sometimes it calls this here: SSLSocket.close();
            //2.) also, sometimes it calls a write operation on this SSLSocket.
            //    but since write can block, I've put this write operation inside an AsyncTask: new WriteAsyncTask().execute(somethingToWrite);
            //    This returns immediately.
            Thread.sleep(1000);
        }
    }
}

And this results logcat like this: 结果是这样的logcat:

01-10 22:39:54.148 I/TEST(10327): run
01-10 22:40:04.150 I/TEST(10327): run

So there are like 10 seconds that misses this thread. 因此,大概有10秒钟会错过此线程。 Why could this happen? 为什么会发生这种情况? There are other threads of course which do blocking network operations. 当然,还有其他线程确实会阻止网络操作。 But why is this particular thread not running? 但是为什么这个特定的线程没有运行?

I also noticed a very strange thing: 我还注意到一个很奇怪的事情:

public void run() {
    while(true) {
        Log.i(LOG_TAG, "tick1");
        Thread.sleep(1000);
        Log.i(LOG_TAG, "tick2");
    }
}

And somehow I get this in the log: 我以某种方式在日志中得到了这个:

01-11 22:06:54.649 I/BGService(10078): tick1
01-11 22:07:50.664 I/BGService(10078): tick2

Between tick1 and tick2 there is one and only one operation: Thread.sleep(1000). 在tick1和tick2之间,只有一个操作:Thread.sleep(1000)。 How can it block for almost a minute? 如何阻塞近一分钟? It is in a Thread, which was started from a Service, but what is the main reason for this huge delay? 它在一个从服务启动的线程中,但是造成这种巨大延迟的主要原因是什么?

Make sure sure you run your Runnable like so: 确保像这样运行Runnable:

Thread t = new Thread(new ServiceHelper());
t.start();

Only then will it be started with as a thread. 只有这样,它才能作为线程启动。

On a side note, what you are doing is running an infinite loop which will take 100% CPU usage. 附带一提,您正在执行的是无限循环,这将占用100%的CPU使用率。 It's possible that Android will kill or heavily throttle your service to allow other services to run properly. Android可能会杀死或严重限制您的服务,以允许其他服务正常运行。

在while循环内部使用类似这样的内容,您将看到结果

Thread.sleep(1000); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM