我想,这是一个愚蠢的问题,但仍然......
在我的应用程序中,我需要按顺序运行重量级任务(当然是在单独的线程中)。所以,我认为 Looper 是我的选择。 AsyncTask 则不然,因为请求可以随时到达,线程安全的东西不是必需的。
长时间使用 android.os.Looper 会快速耗尽 Android 电池吗?
来自 Looper 的 source code
/**
* 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 会很快消耗电池,即使所有 Activity 都关闭,该循环仍在运行。
有谁知道这只是一个神话吗?或者我应该选择其他类(class)来解决我的问题?
感谢您的宝贵时间。
最佳答案
嗯。这取决于您发送到此循环程序的消息数量和频率。尽管它以无限循环运行,但此实现将在 queue.next()
中等待下一条消息以继续处理。在等待中,looper 不消耗任何东西。如果你要不断地发送很多消息,那么无论你使用looper还是其他任何东西都没有任何区别。您的代码将运行并消耗电池。
关于android - android.os.Looper 会耗尽电池电量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18650862/