判断一个应用中有多少个Looper

private int getLooperCnt() {
        Looper mainLooper = Looper.getMainLooper();

        int looperCnt = 0;
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for (Thread thread : threadSet) {
            if (thread.getThreadGroup() == Thread.currentThread().getThreadGroup()) {  // 这里的currentThread在这里的情况是UI线程
                try {
                    Field field = mainLooper.getClass().getDeclaredField("sThreadLocal");
                    field.setAccessible(true);
                    ThreadLocal<Looper> threadLocal= (ThreadLocal<Looper>)field.get(mainLooper);
                    Looper looper = threadLocal.get();
                    if (looper != null) {
                        looperCnt++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return looperCnt;
    }

这里的思路就是:

(1)找出系统上所有的线程;

(2)判断是否给UI线程同一个线程组,如果是说明这些线程是同一个app的;

(3)通过反射获取mainLooper中的,

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();


测试代码:

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int looperCnt = getLooperCnt();
                Toast.makeText(getApplicationContext(), "Looper count: " + looperCnt, Toast.LENGTH_SHORT).show();
            }
        });

for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                        }
                    };
                    Looper.loop();
                }
            }).start();
        }


//---------------------------------------------------------------------------------------------------------------------------------------------------

http://stackoverflow.com/questions/1323408/get-a-list-of-all-threads-currently-running-in-java

To get an iterable set:

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

To convert it to an array:

Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);

你可能感兴趣的:(判断一个应用中有多少个Looper)