views:

68

answers:

0

Hey guys, so I have been getting this really weird bug in my android app that I have isolated down to the fact that a handler is not being created. The odd part, is that despite the fact 5 threads are being created, under certain circumstances...only 4 handlers are created. And then the rest of the time, 5 handlers are being created. Now I am kind of confused on how exactly this is happening since it is the exact same code...

In the case of the 4 Handlers being created, I am unable to exit one of the threads due to it being stuck in a looper. This means I can't return any data, and also just destroys the battery life of the phone.

Here's a code snippit, can anyone explain this problem to me?

    private ArrayList<Thread> t = new ArrayList<Thread>();
private Vector<Handler> h = new Vector<Handler>();
private Vector<Integer> isDone = new Vector<Integer>();

for (int i = 0; i < 5; i++) {
        t.add(new Thread() {
            public void run() {
                Looper.prepare();
                h.add(new Handler());
                Looper.loop();
                isDone.add(1);
                System.out.println(isDone.size());
                System.out.println("H" + h.size());
                System.out.println("T" + t.size());
            }
        });
    }
    for (Thread thread : t)
        thread.start();

Runnables posted to handlers before posting this code to each handler that was created.

    for (Handler hand : h) {
            hand.post(new Runnable() {
                @Override
                public void run() {
                    Looper.myLooper().quit();
                }
            });
        }