糖葫芦


  • Startseite

  • Tags

  • Archiv

  • Suche

LeakCannary原理分析

Veröffentlicht am 2018-11-07 |

上篇写到 leakcanary 的使用,这篇主要是了解LeakCannary 大概是如何工作的。

1.首先它是如何监听Activity 销毁的?

因为我们知道只有当activity 销毁(onDestroy())的时候,我们才能对这个activity 进行分析查看哪些对象可能存在内存泄漏。

发现了如下代码:

1
2
3
4
5
public static RefWatcher install(Application application) {
return refWatcher(application).listenerServiceClass(DisplayLeakService.class)
.excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
.buildAndInstall();
}

在buildAndInstall() 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public RefWatcher buildAndInstall() {
....
if (refWatcher != DISABLED) {
if (watchActivities) {
//这是观察activity的
ActivityRefWatcher.install(context, refWatcher);
}
if (watchFragments) {
FragmentRefWatcher.Helper.install(context, refWatcher);
}
}
LeakCanaryInternals.installedRefWatcher = refWatcher;
return refWatcher;
}

1
2
3
4
5
6
7
8
public final class ActivityRefWatcher {
....
public static void install(Context context, RefWatcher refWatcher) {
Application application = (Application) context.getApplicationContext();
ActivityRefWatcher activityRefWatcher = new ActivityRefWatcher(application, refWatcher);
//拿到application,注册activity的生命周期回调
application.registerActivityLifecycleCallbacks(activityRefWatcher.lifecycleCallbacks);
}

其中这个:lifecycleCallbacks 就是回调监听

1
2
3
4
5
6
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
new ActivityLifecycleCallbacksAdapter() {//监听activity销毁
@Override public void onActivityDestroyed(Activity activity) {
refWatcher.watch(activity);
}
};

那么我们也可以通过application 注册获取activity 的生命周期监听回调,如下是我写的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class LifeCircleActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.life_layout);

final Application application = (Application) getApplicationContext();
application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.i("xx","activity is onActivityCreated...");
}

@Override
public void onActivityStarted(Activity activity) {
Log.i("xx","activity is onActivityStarted...");
}

@Override
public void onActivityResumed(Activity activity) {
Log.i("xx","activity is onActivityResumed...");
}

@Override
public void onActivityPaused(Activity activity) {
Log.i("xx","activity is onActivityPaused...");
}

@Override
public void onActivityStopped(Activity activity) {
Log.i("xx","activity is onActivityStopped...");
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.i("xx","activity is onActivitySaveInstanceState...");
}

@Override
public void onActivityDestroyed(Activity activity) {

application.unregisterActivityLifecycleCallbacks(this);
Log.i("xx","activity is onDestroy...");
}
});
}

这样我们就可以监听我们当前这个类的生命周期了,可以运行打印日志就知道了。

2.内存泄漏的对象的引用路径

这块使用到了 square 的另一个开源库 haha ,获取当前内存中的heap堆信息的snapshot

Unbenannt

Veröffentlicht am 2018-11-07 |
  • build gradle配置

    1
    2
    3
    4
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.1'
    releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
    // Optional, if you use support library fragments:
    debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.1'
  • 配置 application

    1
    2
    3
    4
    5
    6
    7
    8
    private RefWatcher refWatcher;

    public static RefWatcher getRefWatcher(Context context){

    HealthApplication application = (HealthApplication) context.getApplicationContext();

    return application.refWatcher;
    }
  • 监测

    1
    2
    RefWatcher refWatcher = MyApplication.getRefWatcher(this);//1
    refWatcher.watch(this);

例如:我们写一个泄漏的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_event_bus);

RefWatcher refWatcher = MyApplication.getRefWatcher(this);//1
refWatcher.watch(this);


Message message = Message.obtain();
message.obj = "qianqian";
message.what = 666;
handler.sendMessageDelayed(message,600000);
}

Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i("xx","handle message");
}
};

public void sendMessage(View view){
finish();
}

界面上一个按钮,点击按钮退出程序,在程序 onCreate 方法中我们发送了一个延时的消息,按照我们的分析,肯定会发生泄漏的。来我们看下leakcannary 给我们的提示:

image.png

我们知道当我们退出程序的时候 MessageQueue 中的消息还没执行完毕,MessageQueue.mMessages 这个变量持有的是Message 这个对象,而 Message.target中的 target持有的该Activity的 handler引用,所以此时finish 掉的 activity 并不会被回收,导致LeakActivity 发生内存泄漏。

  • 其中一种解决办法呢,就是我们可以通过在点击或activity 退出时,removeMessage,例如:
    1
    2
    3
    4
    public void sendMessage(View view){
    handler.removeMessages(666);
    finish();
    }

这样就不会有警告了。

也可以通过静态内部类+弱引用的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static class MyHandler extends Handler {
private final WeakReference<LeakActivity> mActivity;

public MyHandler(SampleActivity activity) {
mActivity = new WeakReference<LeakActivity>(activity);
}

@Override
public void handleMessage(Message msg) {
LeakActivityactivity = mActivity.get();
if (activity != null) {
...
}
}
}
private final MyHandler handler= new MyHandler(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_event_bus);
Message message = Message.obtain();
message.obj = "qianqian";
message.what = 666;
handler.sendMessageDelayed(message,600000);
}
}

在实际项目中,可以用这个工具筛查一遍。

EventBus 源码分析(下篇)

Veröffentlicht am 2018-10-08 |

上篇 EventBus 源码分析(上篇) 说到注册订阅的前半部分,此篇用来分析发送事件到接收事件这个过程。

1. 发送事件

示例:

1
EventBus.getDefault().post(new RemindBean("2018-02-12","happy"));

post:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** Posts the given event to the event bus. */
public void post(Object event) {
- 1.获取当前线程的postingThreadState 对象
PostingThreadState postingState = currentPostingThreadState.get();
- 2. 获取里面那个事件队列
List<Object> eventQueue = postingState.eventQueue;
- 3. 将事件添加到队列中去
eventQueue.add(event);

- 4. 判断当前的event 是否在 posting
if (!postingState.isPosting) {
- 5. 是否是主线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
- 6. 判断是否取消
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {//不为空,进入循环
- 7.按照顺序,post一个 remove一个
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}

PostingThreadState 大概看一眼

1
2
3
4
5
6
7
8
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}

再就是 postSingleEvent(eventQueue.remove(0), postingState); 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
- 1. 获取event的字节码(例如就是:RemindBean.class)
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;

if (eventInheritance) {//默认为true
- 2. 根据eventClass 的字节码查找
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
- 3.循环遍历
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
- 4.根据事件,字节码查找订阅者
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}

postSingleEventForEventType:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
- 1.根据字节码取出subscriptions,还记得我们之前在subscribe这个方法的时候,
把subscrber,subscriberMethod 封装成一个subscription 对象。

subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
- 2. 取出每一个subscription 对象
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
- 3. post到相应的线程中回调
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}

postToSubscription: 根据定义的不同线程,调用相应的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case POSTING://一般没定义的,这个就是post在哪个线程,响应就在哪个线程执行
invokeSubscriber(subscription, event);
break;
case MAIN:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BACKGROUND:
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
case ASYNC:
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}

invokeSubscriber:

1
2
3
4
5
6
7
8
9
10
void invokeSubscriber(Subscription subscription, Object event) {
try {
- 反射拿到字节码clazz 反射调用方法,就收到消息了
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}

end.

Eventbus 源码分析(上篇)

Veröffentlicht am 2018-10-08 |

可用于应用内的消息事件传递,方便快捷,耦合性低

1.基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class EventBusMain extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);


EventBus.getDefault().register(this);

}

- 订阅的事件 onEvent1
@Subscribe
public void onEvent1(RemindBean bean){

}
- 订阅的事件 onEvent2
@Subscribe
public void onEvent2(UserInfo bean){

}

@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}

需要发送消息传递的时候:

1
EventBus.getDefault().post(new RemindBean())

2.源码解读

放上官网的一张原理图,感觉挺清晰的:

image.png

发布消息的一方(Publisher),只需要 post 一个 event 之后就不用管了,EventBus 内部会将event逐一分发给订阅此 event 的订阅者(Subscriber). 不错就是这样一个东西。

还记得以往我要实现两个不同的activity 之间要传递一些数据的时候,我都是通过定义一个interface的形式完成,时间一长,定义的接口一堆,在回顾查看代码也确实不够美观。好了话不多说,看下大家都在用的Eventbus.

3.首先

1
EventBus.getDefault().register(this);

getDefault():

1
2
3
4
5
6
7
8
9
10
11
12
EventBus 是一个单例模式,懒汉式,双重判断
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

register 是什么意思呢,就是就跟你订阅报纸一样,报社需要确定几个重要的问题:

  • 订阅者是谁(Subscriber)?
  • 订阅的什么报纸(Event) ?

就是我认为比较重要的,那么register 这一步就是Subscriber 告诉 报社,订阅的event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void register(Object subscriber) {
- 1.先拿到这个订阅者(subscriber)类的字节码
Class<?> subscriberClass = subscriber.getClass();

- 2. 通过这个类的字节码,拿到所有的订阅的 event,存放在List中
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

synchronized (this) {
- 3. 循环遍历所有的订阅的方法,完成subscriber 和 subscriberMethod 的关联
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}

我们看下这个如何根据subscriberClass 找到这个订阅的 method的,findSubscriberMethods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
- 1.先从缓存中取
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);

- 2. 第一次肯定 null
if (subscriberMethods != null) {
return subscriberMethods;
}

- 3. 查找默认也是false,感兴趣的可以看下
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {

- 4. 所以是走这里
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
- 5. 找到之后添加到缓存中,key是 subscriber ;value 是:methods
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}

看下:findUsingInfo(subscriberClass)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
- 1. 我认为就是准备一个查找结果得存储对象
FindState findState = prepareFindState();

- 2. 将订阅者的subscriberClass 存储起来,保存在一个FindState 类中的subscriberClass
同时赋值给clazz变量中,以下代码能够看出
// void initForSubscriber(Class<?> subscriberClass) {
// this.subscriberClass = clazz = subscriberClass;
//}
findState.initForSubscriber(subscriberClass);

while (findState.clazz != null) {进入循环中
//获取subscriberInfo 信息,返回null
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
- 3. 进入到这里了
findUsingReflectionInSingleClass(findState);
}
- 4. 查找父类中的方法
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}

findUsingReflectionInSingleClass 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
- 1. 通过订阅者的字节码查找当前类中所有生命的方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
- 2. 循环遍历所有的方法
for (Method method : methods) {
- 3. 获取方法的修饰符
int modifiers = method.getModifiers();

- 4.判断修饰符,订阅方法的修饰符不能是private,static
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
- 5. 获取方法的所有的参数
Class<?>[] parameterTypes = method.getParameterTypes();

- 6.判断参数的个数,只能有1个参数,订阅方法中
if (parameterTypes.length == 1) {
- 7.获取方法上具有subscribe 注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);

- 8.含有subscribe注解的方法,就是该类订阅的方法,其它不符合的可能就是普通的方法
if (subscribeAnnotation != null) {

- 9. 获取第一个参数eventType
Class<?> eventType = parameterTypes[0];

if (findState.checkAdd(method, eventType)) {
- 10. 获取注解的mode,就是我们在注解上标识的,
有mainThread,Posting,background,async
ThreadMode threadMode = subscribeAnnotation.threadMode();

- 11. 将订阅方法的一系列信息(方法名称,threadMode,优先级,是否是粘性等)添加到集合subscriberMethods中去
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
- 12. 参数是多个的时候抛出异常
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
- 13. 方法的修饰符不是public的,抛出异常

String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}

这样我们将所有信息都保存到findState 类中去了。再回头看我们原先那个方法,到第三步了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
- 1. 我认为就是准备一个查找结果得存储对象
FindState findState = prepareFindState();

- 2. 将订阅者的subscriberClass 存储起来,保存在一个FindState 类中的subscriberClass
同时赋值给clazz变量中,以下代码能够看出
// void initForSubscriber(Class<?> subscriberClass) {
// this.subscriberClass = clazz = subscriberClass;
//}
findState.initForSubscriber(subscriberClass);

while (findState.clazz != null) {进入循环中
//获取subscriberInfo 信息,返回null
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
- 3. 进入到这里了,上面已经分析所有信息保存到findState中
findUsingReflectionInSingleClass(findState);
}
- 4. 查找父类中的方法
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}

在这个getMethodsAndRelease(findState):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
- 1. 取出里面的subscriberMethods
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
- 2. 返回集合
return subscriberMethods;
}

至此,我们知道了根据订阅者(subscriber)的clazz 找到了所有订阅的方法事件
methods

回到最初的第一步register:

1
2
3
4
5
6
7
8
9
10
11
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
- 2. 完成
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
- 3.循环遍历所有的订阅方法和订阅者之间建立关联
subscribe(subscriber, subscriberMethod);
}
}
}

subscribe(subscriber, subscriberMethod) 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
- 1. 订阅方法的eventType的字节码
Class<?> eventType = subscriberMethod.eventType;

- 2. 订阅者和订阅方法封装成一个Subscription 对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);

- 3. subscriptionsByEventType 第一次也是null ,根据eventType
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);

- 4. 第一次肯定为null
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();

- 5. key 为 eventType, value 是subscriptions对象
subscriptionsByEventType.put(eventType, subscriptions);
} else {
- 抛出异常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}

- 6. 获取所有添加的subscriptions
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
- 7. 会判断每个订阅方法的优先级,添加到这个 subscriptions中,按照优先级
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}

- 8.获取订阅的方法集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
- 9. 为空添加到 typesBySubscriber
typesBySubscriber.put(subscriber, subscribedEvents);
}
- 10. 订阅事件添加到subscribedEvents集合中去
subscribedEvents.add(eventType);

- 11. 判断是否是粘性事件的关联
if (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}

到此,如果你跟着我一步步看到这里,应该大概明白一些了,还有一部分没完,就是register 前半部分完成订阅,存储等工作;剩下post(event) 方法就是将event 分发给相应订阅过此事件的订阅者了。

AsyncTask源码解读

Veröffentlicht am 2018-09-19 |

屡思路

1. 初始 AsyncTask

AsyncTask 这个类的声明如下:

1
2
3
4

public abstract class AsyncTask<Params, Progress, Result> {
.....
}

是一个抽象类
Params 表示输入参数的类型
Progress 表示后台任务的执行进度
Result 表示返回结果的类型

2.使用

在 AsyncTask 这个类的顶部有一些代码注释,里面讲述了如何使用一个 AsyncTask,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
* <p>Here is an example of subclassing:</p>
* <pre class="prettyprint">
* private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
* protected Long doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* // Escape early if cancel() is called
* if (isCancelled()) break;
* }
* return totalSize;
* }
*
* protected void onProgressUpdate(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* protected void onPostExecute(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>

//user
<p>Once created, a task is executed very simply:</p>
* <pre class="prettyprint">
* new DownloadFilesTask().execute(url1, url2, url3);
* </pre>

3. 内部重要方法

  • onPreExecute()
    1
    2
    3
    @MainThread
    protected void onPreExecute() {
    }

在主线程中运行,异步任务之前会被调用,一般用于做一些准备工作;

  • doInBackground()
    1
    2
    @WorkerThread
    protected abstract Result doInBackground(Params... params);

在线程池中运行,此方法一般用于执行异步任务,通过publishProgress 方法来更新进度;

  • onProgressUpdate()
    1
    2
    3
    @MainThread
    protected void onProgressUpdate(Progress... values) {
    }

主线程中运行,当通过publishProgress 方法调用后,onProgressUpdate() 方法会被调用;

  • onPostExecute()
    1
    2
    3
    @MainThread
    protected void onPostExecute(Result result) {
    }

主线程中运行,将返回的结果展示。

4.源码分析

从它的 execute 方法开始:

1
2
3
4
5
6
7
8
 @MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
//sDefaultExecutor 定义如下,线程池
return executeOnExecutor(sDefaultExecutor, params);
}

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//首先判断是不是 PENDING
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
//将状态设置为 RUNNING 状态
mStatus = Status.RUNNING;
//1.调用了 onPreExecute() 方法
onPreExecute();
//将参数封装到 mWorker.mParams 中去了
mWorker.mParams = params;
//调用execute 将mFuture 传进去了
exec.execute(mFuture);

return this;
}

为了弄明白整体流程,首页要搞明白上面的 mWorker mFuture 是干嘛的。

  • mWorker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 private final WorkerRunnable<Params, Result> mWorker;
//抽象类 并且实现了Callable 接口
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}

@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;

AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//在AsyncTask 的构造方法中,分别对 mWorker, mFuture 进行了初始化
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);

mWorker = new WorkerRunnable<Params, Result>() {
//实现 了 call 方法
public Result call() throws Exception {
//设置调用了为 true
mTaskInvoked.set(true);
//
Result result = null;
try {

//设置线程的优先级
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//将 2. doInBackground的结果存储到 result 中
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//最后执行postResult
postResult(result);
}
//返回结果
return result;
}
};

mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}

postResult(result) 方法

1
2
3
4
5
6
7
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}

发送一条 MESSAGE_POST_RESULT 的消息,并且将result 存入到了 AsyncTaskResult中的 mData 中去了,
其中 AsyncTaskResult

1
2
3
4
5
6
7
8
9
10
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;

AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}

getHandler 获取一个 Handler ,我们看下 handleMessage 的MESSAGE_POST_RESULT 对这条消息的处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}

@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
//是他是他 就是他
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}

其中 result 是 AsyncTaskResult 类型,前面我们见到过的,mTask 当时我们传的是 this 也就是当前的 AsyncTask ,调用finish 方法,将mData 返回的结果传入进去,还记得我们前面看过的吗,将返回的结果存入AsyncTaskResult.mData中去了。

下面看下 finish方法:

1
2
3
4
5
6
7
8
9
10
11
private void finish(Result result) {
//判断是否取消,如果取消了,就不执行onPostExecute 了
if (isCancelled()) {
onCancelled(result);
} else {
//4. 就执行onPostExecute 方法了
onPostExecute(result);
}
// 将状态标志为 finish
mStatus = Status.FINISHED;
}

ok ,上述都是 mWorker 工作的,接下来是我们一开始说的 mFuture

  • mFuture
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    private final FutureTask<Result> mFuture;

    //初始化也是在AsyncTask 构造方法中执行的,在mWorker 之下,并且将mWorder 传入
    mFuture = new FutureTask<Result>(mWorker) {
    @Override
    protected void done() {
    try {
    postResultIfNotInvoked(get());
    } catch (InterruptedException e) {
    android.util.Log.w(LOG_TAG, e);
    } catch (ExecutionException e) {
    throw new RuntimeException("An error occurred while executing doInBackground()",
    e.getCause());
    } catch (CancellationException e) {
    postResultIfNotInvoked(null);
    }
    }
    };

postResultIfNotInvoked(get()); 如下:

1
2
3
4
5
6
7
8
9
10
11
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
//wasTaskInvoked 为true ,之前在 mWorker 中设置了为true
//mWorker = new WorkerRunnable<Params, Result>() {
// public Result call() throws Exception {
// mTaskInvoked.set(true);

if (!wasTaskInvoked) {
postResult(result);
}
}

FutureTask :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
我们知道mWorker implement Callable 接口,传入赋值给了callable 变量
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}

public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
//callable 变量又赋值给了 c
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//这里调用c.call 实际上就是调用 mWorker.call 方法
//,由我们上面的分析知道,在mWorker.call 方法中最终会返回 result 结果
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}

ok ,这是 mFuture,还剩下最后一个:

exec.execute(mFuture);

exec 就是 sDefaultExecutor ,其实 就是 SerialExecutor,如下:

1
2
3
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

SerialExecutor 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;

public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
//第一次肯定为null ,执行 scheduleNext
if (mActive == null) {
scheduleNext();
}
}

protected synchronized void scheduleNext() {
//给 mActivie 赋值,mTasks.poll 会从第一个开始取
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}

上面我们将 mFuture 传入,实际就是 r.
mTask 是 ArrayDeque<Runnable> 姑且认为它是这个排队序列的吧。看下offer 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
插入一个 element 在队尾
* Inserts the specified element at the end of this deque.
*
* <p>This method is equivalent to {@link #offerLast}.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}

看注释,也就是说是每次执行一个任务,都是在当前 deque 的队尾开始排队的。并且执行是串行的,因为当第二个线程过来的时候,判断 mActive 不为 null 将不会执行 scheduleNext.(我这个是8.0)源码,其实在 android 3.0 之后 AsyncTask 都是采用串行执行任务的。

各个版本的不同如下:
android 1.6之前 —— 串行
android 1.6-3.0 之间 —– 并行
android 3.0 之后 —– 串行

尽管如此,我们仍然可以通过 调用 executeOnExecutor 来并行执行任务。

ok , 回到那个 execute 方法中,我们说调用了 r.run 实际山就是 调用 mFuture.run 方法:
上面我们展示过在 mFuture.run 方法中如下:

1
2
3
4
5
6
7
8
9
10
try {
//这里调用c.call 实际上就是调用 mWorker.call 方法
//,由我们上面的分析知道,在mWorker.call 方法中最终会返回 result 结果
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}

最终调用mWorker.call 方法,而在 mWorker.call 方法中,我们完成一系列的任务,调用了 doInBackground onPostExecute 完成了整个的调用过程。

有的人可能已经注意到了 还差一个 onProgressUpdate 方法还没被调用,我们知道只有调用那个 publishProgress 方法的时候才能调用 onProgressUpdate ,那下面我们卡夏 publishProgress 方法:

1
2
3
4
5
6
7
8
@WorkerThread
protected final void publishProgress(Progress... values) {
//如果没取消
if (!isCancelled()) {
//会发送一个 MESSAGE_POST_PROGRESS 的消息 getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}

@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS://是他是他 就是他
//3. 调用了 onProgressUpdate 方法了
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}

会调用 AsyncTask 的 onProgressUpdate 方法了。结束。

总结

AsyncTask 实现原理就内部维护了2个线程池+Handlder,2个线程池分别为:任务队列 线程池(SerialExecutor),执行 线程池(Thread_pool_executor)真正执行具体的线程任务,任务完成最后通过 InternalHandler 发送消息 ,将执行任务的结果post 到主线程中。此线程池中执行任务的顺序,根据不同 api 版本的不同顺序略有不同,在android 1.6之前,是串行执行任务,在 Android 1.6-3.0 之间通过并行执行任务,Android 3.0之后就是默认串行执行任务了,当然我们也可以通过调用executeOnExecuteor 并行执行。

Service 启动过程

Veröffentlicht am 2018-09-11 |

看完 Activity 的启动过程,发现 Service 的启动过程相对来说就比较简单了。

要说起启动过程,就得从 startService 开始:

1.startService

根据源码的跳转,发现跳转到 ContextWrapper 这个类中,代码如下:

1
2
3
4
@Override
public ComponentName startService(Intent service) {
return mBase.startService(service);
}

其中 mBase 是类型是:Context 类型,如下:

1
2
3
4
public class ContextWrapper extends Context {
Context mBase;
......
}

而我们又知道 Context 是一个抽象类 ,实现者是 ContextImpl ,所以我们应该是查看ContextImpl 这个类中的 startService(service) 方法。

ContextImpl 中的方法定义如下:

1
2
3
4
5
@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service, false, mUser);
}

在 startService 中又调用了 startServiceCommon(service,(requirForeground:false),mUser) 这个方法,继续跟进:

2.startServiceCommon

startServiceCommon 方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private ComponentName startServiceCommon(Intent service, boolean requireForeground,
UserHandle user) {
try {
//校验要启动的service
validateServiceIntent(service);
service.prepareToLeaveProcess(this);
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), requireForeground,
getOpPackageName(), user.getIdentifier());
if (cn != null) {
if (cn.getPackageName().equals("!")) {
throw new SecurityException(
"Not allowed to start service " + service
+ " without permission " + cn.getClassName());
} else if (cn.getPackageName().equals("!!")) {
throw new SecurityException(
"Unable to start service " + service
+ ": " + cn.getClassName());
} else if (cn.getPackageName().equals("?")) {
throw new IllegalStateException(
"Not allowed to start service " + service + ": " + cn.getClassName());
}
}
return cn;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}

这里面有几个需要说明一下:

  • ActivityManager.getService() 点进去查看
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    /**
    * @hide
    */
    public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
    }

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
    new Singleton<IActivityManager>() {
    @Override
    protected IActivityManager create() {
    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
    final IActivityManager am = IActivityManager.Stub.asInterface(b);
    return am;
    }
    };

首先是返回的类型是 IActivityManager 类型,其中在create 方法中,拿到远程服务的Binder 对象,其中IActivityManager.Stub.asInterface(b) 不知道大家有没有想起AIDL 这就很熟悉了,就是拿到远程服务的代理对象:IActivityManager,通过代理对象调用远程的方法,是应用进程与服务进程通信的媒介,如果没猜错的话就是在ActivityManagerService 中实现了,查看ActivityManagerService 类:

1
2
3
4
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
.....
}

果然不出所料,AMS extend IActivityManager.Stub .

  • mMainThread.getApplicationThread() 首先明白 mMainThread 是 ActivityThread 类的实例变量,通过getApplicationThread() 方法拿到一个 ApplicationThread 类的实例:
    1
    2
    3
    4
    public ApplicationThread getApplicationThread()
    {
    return mAppThread;
    }

而ApplicationThread 类定义如下:

1
2
3
private class ApplicationThread extends IApplicationThread.Stub {
.....
}

发现 ApplicationThread 是 ActivityThread 的一个内部类.并且实现了 IApplicationThread.Stub ,而我们又把这个类型传入给了AMS,相当于远程服务拿到了一个访问应用进程的代理,类型为:IApplicationThread

总结:到目前为止,客户端拿到了远程服务的代理(IActivityManager), 服务端拿到了客户端的代理(IApplicationThread),它们互相拿到各自进程的代理类,是它们进行进程间通信的基础。

ok ,我们回到最初那个地方:

1
2
3
4
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), requireForeground,
getOpPackageName(), user.getIdentifier());

通过前面的分析我们知道:ActivityManager.getService(). 实际就是 AMS 远程代理,最终在AMS 中完成,我们去 AMS 代码中查看下 startService 代码:

3.ActivityManagerService. startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Override
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, boolean requireForeground, String callingPackage, int userId)
throws TransactionTooLargeException {
enforceNotIsolatedCaller("startService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}

if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}

if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
"*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
synchronized(this) {
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
ComponentName res;
try {
// 又调用了startServiceLocked 方法
res = mServices.startServiceLocked(caller, service,
resolvedType, callingPid, callingUid,
requireForeground, callingPackage, userId);
} finally {
Binder.restoreCallingIdentity(origId);
}
return res;
}
}

startServiceLocked 方法很复杂,大概如下:

1
2
3
4
5
6
7
8
9
10
11
ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
throws TransactionTooLargeException {

.....
ServiceRecord r = res.record;//启动service的信息保存在 serviceRecord 中
....
ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
return cmp;
.....
}

内部又调用了:startServiceInnerLocked 方法

4.startServiceInnerLocked

如下:

1
2
3
4
5
6
ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
...
String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
...
}

又调用: bringUpServiceLocked

5.bringUpServiceLocked

1
2
3
4
5
6
7
 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
....

realStartServiceLocked(r, app, execInFg);
}

而后又调用了 realStartServiceLocked(r, app, execInFg);

6.realStartServiceLocked

1
2
3
4
5
6
7
8
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
....
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
....
}

其中 app.thread 是 IApplicationThread 类型,就是远程调用客户端进程里的方法,scheduleCreateService ,而我们又知道 ApplicationThread 实现了 IApplicationThread,所以就查看 ApplicationThread 类中的 scheduleCreateService方法,前面我们说过ApplicationThread 是 ActivityThread 的一个内部类,查看:

7.ApplicationThread.scheduleCreateService

1
2
3
4
5
6
7
8
9
10
public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();
s.token = token;
s.info = info;
s.compatInfo = compatInfo;

sendMessage(H.CREATE_SERVICE, s);
}

发现内部通过发送一个 CREATE_SERVICE 的消息,H 是 Handle,继续查看:
handleMessage 方法

1
2
3
4
5
case CREATE_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
handleCreateService((CreateServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;

到 handleCreateService 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
private void handleCreateService(CreateServiceData data) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();

LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
service = (Service) cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
if (!mInstrumentation.onException(service, e)) {
throw new RuntimeException(
"Unable to instantiate service " + data.info.name
+ ": " + e.toString(), e);
}
}

try {
if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
//创建context
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);
//创建Application
Application app = packageInfo.makeApplication(false, mInstrumentation);
//通过attach 方法,将context application ,service 连接起来
service.attach(context, this, data.info.name, data.token, app,
ActivityManager.getService());
//调用service oncreate方法
service.onCreate();
mServices.put(data.token, service);
try {
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(service, e)) {
throw new RuntimeException(
"Unable to create service " + data.info.name
+ ": " + e.toString(), e);
}
}
}

service.onCreate(); ok ,调用了 onCreate 方法,至此,service的启动过程的就完成了。

TransitionDrawable

Veröffentlicht am 2018-08-16 |
  • 1.首先创建一个xml 在 drawable 目录下

transition_image

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/first" />
<item android:drawable="@drawable/two" />
</transition>
  • 2.在xml中引用
1
android:drawable="@drawable/transition_image"
  • 3.在Activity中使用
1
2
3
ImageView mImageView = (ImageView) findViewById(R.id.iv); 
TransitionDrawable transitionDrawable = (TransitionDrawable) mImageView.getDrawable();
transitionDrawable.startTransition(3000)

另外一种写法实现多张图片效果

1
2
3
TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{getResources().getDrawable(R.drawable.first),getResources().getDrawable(R.drawable.two)});
mImageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(3000);

小程序的爬坑之路

Veröffentlicht am 2018-07-05 |

近期由于项目需要,需要编写小程序,遇到一些问题,记录下来,也是给自己开发的一个总结。

1.关于模板 template

在看完 官方文档 里的说明之后,我并没有成功使用,按照它那个设置完成后,一直说找不到,最后在知道,原来除了实例那些之外,还要在当前 wxml 中 import 进来。

  • 1.先建一个 template 的文件夹,新建 wxml,根据具体的路径引入进来,例如:
    1
    <import src="../template/line.wxml" />

还有一个就是如果有相对应的 wxss文件,可在 app.wxss文件中引用,这样整个项目都不需要引用这个样式文件了。

注意:模板拥有自己的作用域,只能使用 data 传入的数据以及模版定义文件中定义的 模块。

2. 关于水平居中,垂直居中

一开始感觉这啥玩意,不听话啊,让居中也不居中,就是不动啊,很是郁闷,后来发现了一些规律。

2.1 水平居中

  • 首先如果是行内元素,例如 这样的,如果想水平居中,使用text-align:center 你会发现不好使啊,纹丝不动,原因是因为行内元素长度随内容变化,所以它不能让你在一行的中间,因为它的长度就是文字长度。

解决方案:可以换成view 控件,或者使用:display:block + text-align:center

  • 其它元素可以使用
    1
    2
    3
    4
    5
    6
    ======3个一起使用==========
    text-align:center;
    align-items:center;
    justify-content: center;
    ==================
    margin:auto # 子容器在父容器中居中,单独使用

2.2 垂直居中

1
2
3
4
//可使用如下
display:flex;
align-items:center;
justify-content:center;

3.关于几个控件平分整个屏幕宽度问题

一开始我还想着获取屏幕的宽和高,然后再动态给控件设置具体的值,后来发现有更简单的做法

例如:像这样一行排四个
image.png

解决方案:设置控件的宽度为 :25%,这样就自动平分啦。当然还有其它的方式,但是我认为百分比的这种写法感觉很直观。

4. flex 布局

熟练掌握 flexbox 布局,可以更轻松的编写任何常见的布局,可以查看相关专业的文章。

未完待续…..

Kotlin-可观察属性

Veröffentlicht am 2018-06-27 |

类似于观察者模式,当所监测的对象发生改变时,能够收到回调通知。

例如:我们监测一个变量:

1
2
3
4
5
6
7
8
9
var str: String by Delegates.observable("qianqian",{
property: KProperty<*>, oldValue: String, newValue: String ->
Log.i("xx","改变的属性名称:${property.name} --- ${oldValue} -- ${newValue}" )
})

//点击一个按钮,改变str的值
fun foo(view : View){
str = "haha"
}

这时候我们会发现,当改变str 的值的时候,会打印信息,也就是收到回调:

1
改变的属性名称:str --- qianqian -- haha

再比如:检测对象里的其中一个属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import kotlin.properties.Delegates

class User {
var name: String by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
}

fun main(args: Array<String>) {
val user = User()
user.name = "first"
user.name = "second"
}

打印信息:

1
2
<no name> -> first
first -> second

Kotlin let with run also apply区分

Veröffentlicht am 2018-04-28 |

image.png

apply

它与其它特殊之处在于,它返回本省对象:

1
public inline fun <T> T.apply(block: T.() -> Unit): T {}

例如:

1
2
3
4
5
6
ArrayList<String>().apply {
add("qq")
add("mi")
}.let {//this->ArrayList本身
Log.i("xx","list==="+it)
}

打印结果:

1
list===[qq, mi]

这里T 就是 ArrayList<String>() 返回对象本身,也就是ArrayList

  • 内部是 this 还是 it 这个倒没什么,编辑器一般都会有提示,如图:

    1540798437731.png

apply 是 this , also 是 it

run

  • run:

    1
    public inline fun <T, R> T.run(block: T.() -> R): R {}

    返回最后一行,传入block 返回 最后一行,例如:

    1
    2
    3
    4
    5
    6
    7
    ArrayList<String>().run {
    add("lala")
    add("kaka")
    this.get(1)
    }.let {
    Log.i("xx","返回::"+it)
    }

    打印:

    1
    返回::kaka

let

1
public inline fun <T, R> T.let(block: (T) -> R): R {}

也是返回最后一行,但是它内部不能调用对象的方法:

1
2
3
4
5
6
fun letGo(): Int{
"qianqian".let {
Log.i("xx",it)
return 1
}
}

调用letGO 返回 1

with

类似于:apply + let 的结合

1
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {}

例如:

1
2
3
4
5
6
7
with(ArrayList<String>()){
add("haha")
add("heihei")
this//最后返回ArrayList对象
}.let {
Log.i("xx","list==="+it)//打印:[haha,heihei]
}
1…5678

QQabby

79 Artikel
63 Tags
© 2020 QQabby
Erstellt mit Hexo
|
Theme — NexT.Pisces v5.1.3