我想,这是一个愚蠢的问题,但仍然......
在我的应用程序中,我需要按顺序运行重量级任务(当然是在单独的线程中)。所以,我认为,Looper 是我的选择。AsyncTask 并非如此,因为请求可以随时到达,线程安全的东西不是必需的。
长时间使用 android.os.Looper 会快速消耗 android 电池吗?
来自 Looper 的源代码
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
我明白了,这里我们有一个不定式循环,这很好。但是,我仍然担心,在应用程序后台使用此 Looper 会很快消耗电池,即使所有活动都关闭,该循环仍在运行。
有谁知道这只是一个神话?还是我应该选择其他课程来解决我的问题?
感谢您的时间。