gpt4 book ai didi

java - 服务中的线程在主线程中进行了太多工作

转载 作者:行者123 更新时间:2023-12-02 11:46:15 25 4
gpt4 key购买 nike

我正在制作一个应用程序,您可以在服务中运行线程,并使用此 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'

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

最佳答案

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

关于java - 服务中的线程在主线程中进行了太多工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com