Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get AsyncTask's thread name before execute it?

I am doing AOP instrument, I want to record thread generation relation, such as who starts a new async task, so I'd like to get the AsyncTask's thread name before the parent thread calls android.os.AsyncTask.execute. In the AOP's before advice, I can get the AsyncTask object, but looks like asnctask class doesn't provide a public method to get the thread name and thread id. Is there any way to get the asynctask's thread name and thread id before execute it?

Unlike thread's start method, before starting a thread, i can get thread's name and id by calling Thread.getName() and Thread.getId() with the thread object.

============UPDATE==============
I have found a workaround, before calling android.os.AsyncTask.execute, save the asyncTask obj ref and its current thread name(asynctask's parent thread) as a key-value to a map. Then during asyncTask's doInBackground(), call Thread.currentThread().getName() to get the current asynctask's thread name, and use the this asynctask obj ref as key to query the above map, then we can get the thread name of the parent thread. So we can get the generation relation.

like image 383
bettermanlu Avatar asked Apr 24 '26 19:04

bettermanlu


1 Answers

This is code from AsyncTask class:

private static final ThreadFactory sThreadFactory = new ThreadFactory() {
    private final AtomicInteger mCount = new AtomicInteger(1);

    public Thread newThread(Runnable r) {
        return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
    }
};

as you can see thread name always starts with "AsyncTask #" and then number of times you started it;

like image 87
Autocrab Avatar answered Apr 27 '26 07:04

Autocrab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!