首先看bind service时,onServiceConnected是在前台进程的主线程内,但是bindService可以不在主线程里执行
myAIDLInterface.setCallback(callback);这句话会跨进程,调用service内的setCallback,执行service的setCallback是在service的非主线程内(service的oncreate为主线程,setCallback其实是在binder线程中调用的).换句话说,myAIDLInterface.setCallback(callback);会导致后台进程执行setCallback,后台进程会开一个子线程(就是binder线程)来执行setCallback。
线程id如下:
service mainthread id1
set callbackthread id5852
接着,再看mCallback.showTime(count); 这也是跨进程的,会导致前台进程执行showTime(),这是在前台进程的非主线程里执行。也就是说,mCallback.showTime(count); 会导致前台进程启动一个子线程(binder线程)来执行showTime().日志如下,可见每次aidl调用会让前台进程启动一个线程去执行showTime,而且这个线程不是固定的,有时候是5830,有时候是5831.
05-28 22:22:52.319 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ callback3
05-28 22:22:52.319 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ process namecom.example.fish.aidlclient1
05-28 22:22:52.319 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ thread id5830
05-28 22:22:52.319 13421-13421/com.example.fish.aidlclient1 D/FishLog﹕ handleMessage
05-28 22:22:54.319 12514-13435/com.myservice D/FishLog﹕ callback
05-28 22:22:54.319 13421-13433/com.example.fish.aidlclient1 D/FishLog﹕ callback4
05-28 22:22:54.329 13421-13433/com.example.fish.aidlclient1 D/FishLog﹕ process namecom.example.fish.aidlclient1
05-28 22:22:54.329 13421-13433/com.example.fish.aidlclient1 D/FishLog﹕ thread id5831
05-28 22:22:54.339 13421-13421/com.example.fish.aidlclient1 D/FishLog﹕ handleMessage
05-28 22:22:56.349 12514-13435/com.myservice D/FishLog﹕ callback
05-28 22:22:56.349 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ callback5
05-28 22:22:56.349 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ process namecom.example.fish.aidlclient1
05-28 22:22:56.359 13421-13432/com.example.fish.aidlclient1 D/FishLog﹕ thread id5830
05-28 22:22:56.359 13421-13421/com.example.fish.aidlclient1 D/FishLog﹕ handleMessage
总结下:
aidl调用会导致被调用进程启动一个子线程来执行实际代码。
因此后台service通过aidl调用前台进程的话,要注意无法在调用函数体内执行ui更新操作,因为此函数是在非主线程中执行的