2

ばかげた質問だと思いますが、それでも...

私のアプリでは、重いタスクを順番に (もちろん別のスレッドで) 実行する必要があります。だから、これにはルーパーが私の選択だと思います。リクエストはいつでも到着する可能性があり、スレッドセーフなものは必要ないため、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();
    }
}

わかりました、ここに無限ループがありますが、これはかなり問題ありません。それでも、アプリのバックグラウンドでこのルーパーを使用すると、バッテリーが非常に速く消費され、すべてのアクティビティがオフになっている場合でもループが実行されているのではないかと心配しています。

それが単なる神話であることを知っている人はいますか?または、問題を解決するために他のクラスを選択する必要がありますか?

お時間をいただきありがとうございます。

4

2 に答える 2

3

良い。これは、このルーパーに送信するメッセージの数と頻度によって異なります。無限ループで実行されますが、この実装はqueue.next()次のメッセージが処理されるまで待機します。待機中のルーパーは何も消費しません。常に多くのメッセージを送信する場合は、他のルーパーを使用するかどうかに違いはありません。コードが実行され、バッテリーが消費されます。

于 2013-09-06T06:06:56.320 に答える
0

すべてのUIスレッドにはルーパーがあるため、そのような獣ではありません。次を参照してください: queue.next(); // ブロックする可能性があります。ほとんどの時間はここで費やされます

ところで、ルーパーを備えたスレッドである HandlerThread を参照してください。必要なのは、ワーカー Handler を作成することだけです。

于 2013-09-06T06:07:36.510 に答える