Android: registerReceiver代码实现

1. 用户接口registerReceiver

frameworks/base/core/java/android/content/ContextWrapper.java

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {

        return mBase.registerReceiver(receiver, filter);

    }

frameworks/base/core/java/android/app/ContextImpl.java

    @Override

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {

        return registerReceiver(receiver, filter, null, null);

    }

    @Override

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,

            String broadcastPermission, Handler scheduler) {

        return registerReceiverInternal(receiver, getUserId(),

                filter, broadcastPermission, scheduler, getOuterContext(), 0);

    }

    @Override

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,

            String broadcastPermission, Handler scheduler, int flags) {

        return registerReceiverInternal(receiver, getUserId(),

                filter, broadcastPermission, scheduler, getOuterContext(), flags);

    }

class ContextImpl extends Context {

……

 

@Override

public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {

return registerReceiver(receiver, filter, null, null);

}

 

@Override

public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,

String broadcastPermission, Handler scheduler) {

return registerReceiverInternal(receiver, filter, broadcastPermission,

scheduler, getOuterContext());

}

 

private Intent registerReceiverInternal(BroadcastReceiver receiver,

IntentFilter filter, String broadcastPermission,

Handler scheduler, Context context) {

IIntentReceiver rd = null;

if (receiver != null) {

// mPackageInfo是一个LoadedApk实例,它是用来负责处理广播的接收的
// context 是通过调用函数getOuterContext得到的

if (mPackageInfo != null && context != null) {

if (scheduler == null) {

// mMainThread.getHandler来获得一个Handler了,

                                        //这个Hanlder是后面用来分发ActivityManagerService发送过的广播用的。

// 这里的成员变量mMainThread是一个ActivityThread实例

scheduler = mMainThread.getHandler();

}

rd = mPackageInfo.getReceiverDispatcher(

receiver, context, scheduler,

mMainThread.getInstrumentation(), true);

} else {

……

}

}

try {

   final Intent intent = ActivityManager.getService().registerReceiver(

           mMainThread.getApplicationThread(), mBasePackageName, rd, filter,

           broadcastPermission, userId, flags);

   if (intent != null) {

       intent.setExtrasClassLoader(getClassLoader());

       intent.prepareToEnterProcess();

   }

   return intent;

} catch (RemoteException e) {

return null;

}

}

 

……

 

}

// BroadcastReceiver

frameworks/base/core/java/android/content/BroadcastReceiver.java

// getHandler()

public final class ActivityThread {

……

final H mH = new H();

 

private final class H extends Handler {

……

 

public void handleMessage(Message msg) {

……

 

switch (msg.what) {

……

}

 

……

}

 

……

 

}

……

 

final Handler getHandler() {

return mH;

}

……

}

// 

frameworks/base/core/java/android/app/LoadedApk.java

    public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,

            Context context, Handler handler,

            Instrumentation instrumentation, boolean registered) {

        synchronized (mReceivers) {

            LoadedApk.ReceiverDispatcher rd = null;

            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;

            if (registered) {

// ArrayMap<Context, ArrayMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers = new ArrayMap<>();
        //由context获得ArrayMap<BroadcastReceiver, ReceiverDispatcher>>
//由BroadcastReceiver获得ReceiverDispatcher

                map = mReceivers.get(context);

                if (map != null) {

                    rd = map.get(r);

                }

            }

            if (rd == null) {

                rd = new ReceiverDispatcher(r, context, handler, instrumentation, registered);

                if (registered) {

                    if (map == null) {

                        map = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();

                        mReceivers.put(context, map);

                    }

                    map.put(r, rd);

                }

            } else {

                rd.validate(context, handler);

            }

            rd.mForgotten = false;

   //获得后就会把它传给ActivityManagerService,以便接收广播

            return rd.getIIntentReceiver();

        }

    }

   
static final class ReceiverDispatcher {

//InnerReceiver实例,这是一个Binder对象,实现了IIntentReceiver接口,

//可以通过ReceiverDispatcher.getIIntentReceiver函数来获得,

                //获得后就会把它传给ActivityManagerService,以便接收广播。

final static class InnerReceiver extends IIntentReceiver.Stub {

final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;

……

InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {

mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);

……

}

……

}

 

……

 

final IIntentReceiver.Stub mIIntentReceiver;

final Handler mActivityThread;

……

ReceiverDispatcher(BroadcastReceiver receiver, Context context,

Handler activityThread, Instrumentation instrumentation,

boolean registered) {

……

 

mIIntentReceiver = new InnerReceiver(this, !registered);

mActivityThread = activityThread;

……

}

……

 

IIntentReceiver getIIntentReceiver() {

return mIIntentReceiver;

}

 

}

 

public class ActivityManagerService extends IActivityManager.Stub

        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

……

 

public Intent registerReceiver(IApplicationThread caller, IIntentReceiver receiver, IntentFilter filter, String permission) {

synchronized(this) {


// 函数首先是获得调用registerReceiver函数的应用程序进程记录块

ProcessRecord callerApp = null;

if (caller != null) {

callerApp = getRecordForAppLocked(caller);

if (callerApp == null) {

……

}

}

 

List allSticky = null;

 

// Look for any matching sticky broadcasts…

Iterator actions = filter.actionsIterator();

if (actions != null) {

while (actions.hasNext()) {

String action = (String)actions.next();

allSticky = getStickiesLocked(action, filter, allSticky);

}

} else {

……

}

 

//广播接收器receiver保存一个ReceiverList列表中,这个列表的宿主进程是rl.app,这里就是MainActivity所在的进程了,
//在ActivityManagerService中,用一个进程记录块来表示这个应用程序进程,它里面有一个列表receivers,

//专门用来保存这个进程注册的广播接收器。接着,又把这个ReceiverList列表以receiver为Key值保存在

//ActivityManagerService的成员变量mRegisteredReceivers中,这些都是为了方便在收到广播时,快速找到对应的广播接收器的

ReceiverList rl

= (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());

if (rl == null) {

rl = new ReceiverList(this, callerApp,

Binder.getCallingPid(),

Binder.getCallingUid(), receiver);

 

if (rl.app != null) {

rl.app.receivers.add(rl);

} else {

……

}

mRegisteredReceivers.put(receiver.asBinder(), rl);

}

  //创建一个BroadcastFilter来把广播接收器列表rl和filter关联起来,
//然后保存在ActivityManagerService中的成员变量mReceiverResolver中去

BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);

rl.add(bf);

……

mReceiverResolver.addFilter(bf);

 

}

}

 

……

 

}

    原文作者:shuai_wen
    原文地址: https://blog.csdn.net/u011279649/article/details/80983020
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞