1

I've been trying for hours to figure this one out and have tried various techniques but can't seem to get a task running in the background. I got this code in my OnClickListener:

new Thread(new Runnable() {
     public void run() {
          //doing some work in the background here
          Log.d(tag, "Thread: " + checkThread());
     }
}).start();

And within the thread, I'm checking if the code was executed on the main/UI thread or background. So I've got this:

private String checkThread() {
    if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
        return "Main";
    } else {
        return "Background";
    }
}

But the above always returns "Main". I've tried Handler, AsyncTask etc. but all of them return the same thing.

Any pointers on how I could get my code to run in the background and also be able to see it in the log that it's not running in the main thread?

Zishan Neno
  • 2,647
  • 7
  • 34
  • 58
  • use https://developer.android.com/guide/components/services.html sticky service will help you it runs o background even if you force close your application – Adeel Turk Dec 27 '16 at 16:37
  • 1
    I copy/pasted exactly your code and it returns me `D/MainActivity: Thread: Background` – Alexander Perfilyev Dec 27 '16 at 17:03
  • Should have mentioned that I'm running Retrofit 2 callback in the background thread and calling `checkThread()` in `onResponse` – Zishan Neno Dec 27 '16 at 17:14
  • 1
    `onResponse` is a callback interface, triggered in current main UI thread, so yes, it can't be on background thread and always returns `Main` – Blo Dec 27 '16 at 17:29
  • Is there any way to get the `onResponse` in the background too? As I'm trying to avoid UI thread locking, would it be a good idea to start a new thread from the response? – Zishan Neno Dec 28 '16 at 06:25
  • I don't think so, it's a callback from a background thread to a current thread, so you'll have to change Retrofit directly or yes, adding a new thread. I don't know what you want to achieve, but you could add to a View queue what you need to do, as `view.post(new Runnable() { ... });` for example ([#2 in this answer](http://stackoverflow.com/a/24035591/2668136)). – Blo Dec 30 '16 at 23:01

1 Answers1

1

My guess is you have to specify the type of thread priority with setThreadPriority. Try as follows:

new Thread(new Runnable() {
     public void run() {
         // moves the current Thread into the background
         android.os.Process.setThreadPriority(
                        android.os.Process.THREAD_PRIORITY_BACKGROUND);

         // doing some work in the background here
         Log.d(tag, "Thread: " + checkThread());
     }
}).start();

This should be return background.

Blo
  • 11,903
  • 5
  • 45
  • 99