我已经尝试了几个小时来解决这个问题,并尝试了各种技术,但似乎无法让任务在后台运行。我在我的 OnClickListener
中得到了这段代码:
new Thread(new Runnable() {
public void run() {
//doing some work in the background here
Log.d(tag, "Thread: " + checkThread());
}
}).start();
在线程内,我正在检查代码是在主/UI 线程还是后台执行的。所以我得到了这个:
private String checkThread() {
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
return "Main";
} else {
return "Background";
}
}
但上面总是返回“Main”。我试过 Handler
、AsyncTask
等,但它们都返回相同的东西。
关于如何让我的代码在后台运行并且能够在日志中看到它没有在主线程中运行的任何指示?
最佳答案
我的猜测是您必须使用 setThreadPriority
指定线程优先级的类型。尝试如下:
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();
这应该是 return background
。
关于android - 在后台运行代码并验证线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348772/