Sriram R
Sriram R

Reputation: 2229

Too much work in main thread from a Thread in Service

I am making an app where you run a thread in a service and it checks the current foreground package using this library

Service Code:

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();
}
}

Basically, I want the thread to run for a given duration given by the user.

When the thread stops after the given duration is over, my app crashes while showing this error

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'

Most of the code is in the thread. Where am I going wrong??

Upvotes: 0

Views: 78

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

you should use start instead of run. run executes the run method. You need to use start() for the thread to begin is execution. Alternatively you can use an IntentService, that is already able to handle asynchronous requests

Upvotes: 1

Related Questions