Reputation: 2817
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?
Upvotes: 1
Views: 186
Reputation: 11988
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
.
Upvotes: 1