服务中的线程在主线程中工作太多

时间:2018-01-10 12:04:57

标签: java android multithreading java-threads

我正在创建一个应用程序,您在服务中运行一个线程,并使用此library

检查当前前台程序包

服务代码:

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'

大多数代码都在线程中。我哪里错了?

1 个答案:

答案 0 :(得分:1)

您应该使用start代替runrun执行run方法。您需要使用start()来开始执行线程。或者,您可以使用已经能够处理异步请求的IntentService