Java 服务线程在主线程中的工作过多

Java 服务线程在主线程中的工作过多,java,android,multithreading,java-threads,Java,Android,Multithreading,Java Threads,我正在制作一个应用程序,其中你在服务中运行一个线程,它会使用这个程序检查当前的前台包 服务代码: public class CheckService extends Service { long startTime; long stopTime; boolean shouldRun = true; private static final String TAG = "CheckService"; final AppChecker appChecker = new AppChecker()

我正在制作一个应用程序,其中你在服务中运行一个线程,它会使用这个程序检查当前的前台包

服务代码:

public class CheckService extends Service {

long startTime;
long stopTime;

boolean shouldRun = true;

private static final String TAG = "CheckService";

final AppChecker appChecker = new AppChecker();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Log.v(TAG,"Thread is still running");
        while(shouldRun){
            Log.v(TAG,"Process running is "+ appChecker.getForegroundApp(getApplicationContext()));
            if (System.currentTimeMillis() - startTime >= stopTime){
                shouldRun = false;
                stopSelf();
                return;
            }
            try{
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {

    startTime = System.currentTimeMillis();
    stopTime = intent.getLongExtra("stop-time",0);

    if (stopTime == 0){
        stopSelf();
    }else{

        Log.v(TAG," Thread is started at "+ String.valueOf(startTime));

        new Thread(runnable).run();
    }

    return Service.START_NOT_STICKY;
}

@Override
public void onDestroy() {
    Log.v(TAG,"Service is destroyed");
    super.onDestroy();
}
}
基本上,我希望线程在用户给定的时间内运行

当线程在给定的持续时间结束后停止时,我的应用程序在显示此错误时崩溃

01-10 17:26:08.541 23317-23317/com.sriram.donotdisturb I/Choreographer: 
Skipped 1207 frames!  The application may be doing too much work on its 
main thread.
01-10 17:26:08.567 23317-23324/com.sriram.donotdisturb I/art: Wrote 
stack traces to '/data/anr/traces.txt'

大部分代码都在线程中。我哪里出错了???

你应该使用
start
而不是
run
<代码>运行执行运行方法。您需要使用
start()
使线程开始执行。或者,您可以使用一个
IntentService
,该服务已经能够处理异步请求

它的可能副本,而不是副本,因为我们的情况不同,我甚至没有注意到这一点。谢谢我知道意向服务。我只是好奇它在开始服务时会如何工作