android之wifi体系架构源码流程分析
一、SystemServer类(frameworks\base\services\java\com\android\Server)
--> 在frameworks\base\cmds\system_server\Library\System_init.cpp中有:
runtime->callStatic("com/android/server/SystemServer", "init2");
/**
* This method is called from Zygote to initialize the system. This will cause the native
* services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
* up into init2() to start the Android services.
*/
说明开机之后就自动执行SystemServer类中的init2方法: public static final void init2() {
Log.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
从中可看出启动了ServerThread线程,其中的run方法创建了很多的服务。我们分析的wifi服务(Connectivity链接服务)中也在run方法中加载:
try {
Log.i(TAG, "Connectivity Service");
connectivity = ConnectivityService.getInstance(context);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
} catch (Throwable e) {
Log.e(TAG, "Failure starting Connectivity Service", e);
}
二、Connectivity类(frameworks\base\core\java\android\Net : extends IConnectivityManager.Stub )
猜测connectivity = ConnectivityService.getInstance(context)是为了得到connectivity这个类。看看:
public static ConnectivityService getInstance(Context context) {
return ConnectivityThread.getServiceInstance(context);
}
为什么它不直接创建 ?
在看看:private static class ConnectivityThread extends Thread 说明这个类文内部静态类, 而且里面有个run方法。
public static ConnectivityService getServiceInstance(Context context) {
ConnectivityThread thread = new ConnectivityThread(context);
thread.start();
...
}
在run中:
public void run() {
Looper.prepare();
synchronized (this) {
sServiceInstance = new ConnectivityService(mContext);
notifyAll();
}
Looper.loop();
}
好!现在已经创建ConnectivityService一个类,并把这个类的对象传到ServerThread线程中的添加服务。
我发现在SystemServer 和Connectivity都启动了一个线程,难道为了创建一个类而启动新线程?肯定不是
,但是却发现run的最后都有Looper.loop();猜测其它很多线程中的最后也有Looper.loop。去搜索Looper.loop,果然,发现looper.loop
都在run方法的最后。由此我猜测:
因为我在使用Handler时,里面有个构造方法Handler(Looper looper) ,所以在线程专递Message时肯定与它有关。
我记得,好像HandlerThread线程会去时不时的处理Message(handlerMessage)队列。然后到handlerThread概看了下,它继承了Thread
类,中的run的方法就有looper.loop。看来最关键的就是这个loop。
那现在到Looper.loop去看下,发现有个MessageQueue queue = me.mQueue;还有个大循环,里面有句 msg.target.dispatchMessage(msg);
跟进去里面实际上最后是调用HandlerMessage方法。
...
接下来在回来在看看Connectivity的构造函数做了什么:
其中有:
if (DBG) Log.v(TAG, "Starting Wifi Service.");
WifiStateTracker wst = new WifiStateTracker(context, mHandler);
WifiService wifiService = new WifiService(context, wst);
ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
还有其它的服务,如:mNetTrackers[ConnectivityManager.TYPE_MOBILE] =
mNetTrackers[ConnectivityManager.TYPE_MOBILE_MMS]=
mNetTrackers[ConnectivityManager.TYPE_MOBILE_SUPL] =
...
我们的wifi服务模块就在其中。现在就有了WifiStateTracker和WifiService。这两个到底起什么用呢?
我去查开发文档,并没有这两个,看来对于应用开发者不可用;开发文档中关于wifi的类就这些:
WifiConfiguration A class representing a configured Wi-Fi network, including the security configuration.
WifiConfiguration.AuthAlgorithm Recognized IEEE 802.11 authentication algorithms.
WifiConfiguration.GroupCipher Recognized group ciphers.
WifiConfiguration.KeyMgmt Recognized key management schemes.
WifiConfiguration.PairwiseCipher Recognized pairwise ciphers for WPA.
WifiConfiguration.Protocol Recognized security protocols.
WifiConfiguration.Status Possible status of a network configuration.
WifiInfo Describes the state of any Wifi connection that is active or is in the process of being set up.
WifiManager This class provides the primary API for managing all aspects of Wi-Fi connectivity.
WifiManager.MulticastLock Allows an application to receive Wifi Multicast packets.
WifiManager.WifiLock Allows an application to keep the Wi-Fi radio awake.
只能到这两个类大概浏览一下了
1)WifiStateTracker类
先看WifiStateTracker构造:我看得眼有点熟的有 mWifiInfo = new WifiInfo();
mWifiMonitor = new WifiMonitor(this);
...
...还很多都不认识。
看方法列表中也只认识:notifyStateChange
notifyXXX
也无意看到handleMessage
我想应该有looper,本文件搜索looper,果然有:
public DhcpHandler(Looper looper, Handler target) {
super(looper);
2) WifiService类
再看一下WifiService(Context context, WifiStateTracker tracker) 构造: mWifiStateTracker = tracker;
HandlerThread wifiThread = new HandlerThread("WifiService");
wifiThread.start();
mWifiHandler = new WifiHandler(wifiThread.getLooper());
这熟悉这几个,其它的几乎不认识;
既然有HandlerThread和 mWifiHandler,那么应该mWifiHandler重写了Handler的某些方法:
再去找一下: private class WifiHandler extends Handler {
public WifiHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_ENABLE_WIFI:
setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
sWakeLock.release();
break;
case MESSAGE_START_WIFI:
mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
mWifiStateTracker.restart();
sWakeLock.release();
break;
case MESSAGE_DISABLE_WIFI:
// a non-zero msg.arg1 value means the "enabled" setting
// should be persisted
setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
sWakeLock.release();
break;
case MESSAGE_STOP_WIFI:
mWifiStateTracker.disconnectAndStop();
// don't release wakelock
break;
case MESSAGE_RELEASE_WAKELOCK:
synchronized (sDriverStopWakeLock) {
if (sDriverStopWakeLock.isHeld()) {
sDriverStopWakeLock.release();
}
}
break;
}
}
}
从中可发现WifiService创建新的线程,那么只谁往这个线程的MessageQueue中放Message的话,这个线程的looper就取出来
然后执行handleMessage。那么谁会往这个线程放Message? 我现在也还不清楚,但是,不是从wifi网卡上来的,就是应用编程吧!
再大概浏览一下方法列表:
public boolean startScan(boolean forceActive)
public boolean setWifiEnabled(boolean enable)
private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid)
private void setWifiEnabledState(int wifiState, int uid)
public boolean enableNetwork(int netId, boolean disableOthers)
private ScanResult parseScanResult(String line)
private void updateWifiState()
...
...
从名字中可看出WifiService类这些方法是用来使能wifi,搜寻ap等等。
跟了那么多代码,应用什么使能wifi呢?肯定要用涉及到 WifiService,然后又什么调到底层?
三、 1)WifiSettings类(packages\apps\settings\src\com\android\settings\Wifi :
extends PreferenceActivity implements WifiLayer.Callback,DialogInterface.OnDismissListener )
从包(app)和父类可以知道这个是一个Activity,也是一个应用程序。
所以看构造和oncreat:
public WifiSettings() {
mAps = new WeakHashMap<AccessPointState, AccessPointPreference>();
mWifiLayer = new WifiLayer(this, this);
}
又出现了个与wifi相关的WifiLayer,不过它与应用相关,先不管它,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onCreatePreferences(); ------------------------->中包含:if (!getIntent().getBooleanExtra(KEY_ONLY_ACCESS_POINTS, false)) {
mWifiEnabled = (CheckBoxPreference) preferenceScreen.findPreference(KEY_WIFI_ENABLED);
mWifiEnabler = new WifiEnabler(this, (WifiManager) getSystemService(WIFI_SERVICE),
mWifiEnabled);
传了一个wifiManager到wifiEnabler,我觉的很重要,因为wifiManager是frameworks\base\wifi\java\android\net\Wifi
这个包的,在看名字Manager,肯定是用它来管理的。而且在开发文档中也有它。等下看看wifiEnabler它什么使用wifiManager。
mWifiLayer.onCreate(); 上面创了WifiEnabler,这里就调用它的oncreat函数。
onCreatedWifi();空的
mWifiLayer.onCreatedCallback();
}
其它的方法调用到了再看吧,下面看看WifiEnabler,之前知道它从系统服务中得到了wifiManager ;
2)WifiEnabler类 packages\apps\settings\src\com\android\settings\Wifi
implements Preference.OnPreferenceChangeListener
其构造函数: public WifiEnabler(Context context, WifiManager wifiManager,
CheckBoxPreference wifiCheckBoxPreference) {
mContext = context;
mWifiCheckBoxPref = wifiCheckBoxPreference;
mWifiManager = wifiManager;
mOriginalSummary = wifiCheckBoxPreference.getSummary();
wifiCheckBoxPreference.setPersistent(false);
mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
}
mWifiStateFilter就是一个IntentFiler, 看到WifiManager.WIFI_STATE_CHANGED_ACTION,猜里面应该有很多宏吧!
大概浏览下发现有个成员类,并创建好了的,说明这个类一创建,也就创建了该类:
private final BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
handleWifiStateChanged(
intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WIFI_STATE_UNKNOWN),
intent.getIntExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE,
WIFI_STATE_UNKNOWN));
} else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
handleNetworkStateChanged(
(NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO));
}
}
};
然后调用handleWifiStateChanged,来处理不同的action!
我们发现这是个广播接收类,重写了onReceive方法:由此上面的IntentFiler 也就不奇怪了,但是还不知道谁发了
广播?
其它方法看了一下,有个
private void setWifiEnabled(final boolean enable) {
// Disable button
mWifiCheckBoxPref.setEnabled(false);
if (!mWifiManager.setWifiEnabled(enable)) {
mWifiCheckBoxPref.setSummary(enable ? R.string.error_starting : R.string.error_stopping);
}
}
正如它的类名一样,使能wifi,而用到的使能类wifiManager,就是wifiManager.setWifiEnabled(enable) ;
又有这个方法private static String getHumanReadableWifiState(int wifiState),看里面是用来
获取wifi当前状态的的方法,在结合广播接收器,可大概知道知道这个类的作用,就是能接收wifi状态的
改变,我们也就能通过该类获取wifi当前的状态,并能使能wifi,也就是通过wifiManager来使能的。
3)上面的分析还有两个类不知道它们什么意思,就是WifiLayer和wifiManager?
我们先看app中的这个wifiLayer,看它用不用到wifiManager,再猜测这个wifiManager,然后再分析这个wifiManager就应该
比较清楚了。
通过上面跟的代码,知道wifiLayer是在wifiSetting类的构造方法创建的:mWifiLayer = new WifiLayer(this, this);
而在wifisetting的oncreat中调用了wifiEnable中的oncreat,
那么我们在先看wifiLayer的构造再看wifiEnable.oncreat:
public WifiLayer(Context context, Callback callback) {
mContext = context;
mCallback = callback;
}
callback是wifiLayer中的一个接口,在看传进来的是this也就是wifiSetting,那么在wifiSetting中肯定实现了这个接口,
看看wifiSetting类, 果真有implements WifiLayer.Callback 。
浏览一下这个接口每个方法的描述:
void onAccessPointSetChanged(AccessPointState ap, boolean added);-->Called when an AP is added or removed.
void onScanningStatusChanged(boolean started); -->Called when the scanning status changes.
void onAccessPointsStateChanged(boolean enabled); -->Called when the access points should be enabled or disabled. This is
called from both wpa_supplicant being connected/disconnected and Wi-Fi
being enabled/disabled.
void onRetryPassword(AccessPointState ap); -->Called when there is trouble authenticating and the retry-password
dialog should be shown.
onCreate中:public void onCreate() {
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mIntentFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
WIFI_NUM_OPEN_NETWORKS_KEPT = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);
}
这里它也从系统服务中得到了一个WifiManager,在动态的创建过滤器, 那么也一定有 BroadcastReceiver,来处理
不同的action。
果然:private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
handleNetworkStateChanged(
(NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO),
intent.getStringExtra(WifiManager.EXTRA_BSSID));
} else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
handleScanResultsAvailable();
} else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
handleSupplicantConnectionChanged(
intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false));
} else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
handleSupplicantStateChanged(
(SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE),
intent.hasExtra(WifiManager.EXTRA_SUPPLICANT_ERROR),
intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0));
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
handleWifiStateChanged(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN));
} else if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
handleSignalChanged(intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, 0));
} else if (action.equals(WifiManager.NETWORK_IDS_CHANGED_ACTION)) {
handleNetworkIdsChanged();
}
}
};
这里有很多handleXXX,说明这个处理更多的状态了。
到这里回头看一下之前的wifiEnabler中的onReceive
它处理的Intent中action的有 :* WifiManager.WIFI_STATE_CHANGED_ACTION
WifiManager.NETWORK_STATE_CHANGED_ACTION
而这wifiLayer处理的action有:WifiManager.NETWORK_STATE_CHANGED_ACTION
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION
WifiManager.SUPPLICANT_STATE_CHANGED_ACTION
* WifiManager.WIFI_STATE_CHANGED_ACTION (上面也有这个)
WifiManager.RSSI_CHANGED_ACTION
WifiManager.NETWORK_IDS_CHANGED_ACTION
不用管它什么处理先。
瞄一眼其它的,还发现在有个Handler,
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_ATTEMPT_SCAN:
attemptScan();
break;
}
}
}
看来是用来处理本线程的Messagequeue。
4) 接下来可以去看看wifiManager了。 现在我还不是很清楚,他能做什么,有什么用。
但是得先思考一下:第一、wifiManager什么时候创建?我猜应该是在addservice时(也就是上面Connectivity中的构造)
WifiStateTracker wst = new WifiStateTracker(context, mHandler);
WifiService wifiService = new WifiService(context, wst);
ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
第二、wifiManager向谁提供服务?谁来管理它?整理一下思路,我们的wifiLayer和wifiEnabler都用到了wifiManager,
所以我猜应该是,系统给我们用来控制wifi使能,查看状态,搜寻ap的类。
第一的猜想是不对的,我从 ServiceManager 类往下找,并没有找到。只发现个 getIServiceManager().addService(name, service);
IServiceManager这只是个接口 ,然后有句:sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
不得在往下了,看不懂了,接口太多。还是去搜WifiManager吧!然后发现如下:
private WifiManager getWifiManager()
{
synchronized (sSync) {
if (sWifiManager == null) {
IBinder b = ServiceManager.getService(WIFI_SERVICE);
IWifiManager service = IWifiManager.Stub.asInterface(b);
sWifiManager = new WifiManager(service, mMainThread.getHandler());
}
}
return sWifiManager;
}
看来应该是,wifiManager = this.(WifiManager) getSystemService(WIFI_SERVICE)时创建的。
看看是不是呢,这个方法在Context类中。
public abstract Object getSystemService(String name);
不过是抽象的方法,在哪里实现呢?
我们去看一下android的开发文档:public abstract Object getSystemService (String name)
Since: API Level 1 Return the handle to a system-level service by name.
The class of the returned object varies by the requested name.
Currently available names are:
WINDOW_SERVICE ("window")
The top-level window manager in which you can place custom windows. The returned object is a WindowManager.
LAYOUT_INFLATER_SERVICE ("layout_inflater")
A LayoutInflater for inflating layout resources in this context.
...
WIFI_SERVICE ("wifi")
A WifiManager for management of Wi-Fi connectivity.
没看到啊!这个开发文档只说返回什么而已,没说在哪里产生。
回到上面我们搜索的private WifiManager getWifiManager() ;看看是什么类:
class ReceiverRestrictedContext extends ContextWrapper 。public class ContextWrapper extends android.content.Context
这回有联系了,我猜这里肯定有抽象方法 getSystemService的实现。
果然。 } else if (WIFI_SERVICE.equals(name)) {
return getWifiManager();
终于找到了。
现在就分析这个WifiManager 类
sWifiManager = new WifiManager(service, mMainThread.getHandler())
public WifiManager(IWifiManager service, Handler handler) {
mService = service;
mHandler = handler;
}
这个类比想象的简单啊!
首先他确实有很多宏。 我前面分析的是,应用程序这个wifiManager来控制wifi网卡状态,比如:使能,搜寻ap等等,
但是却发现,return mService.startScan(false);
return mService.enableNetwork(netId, disableOthers);
return mService.disconnect();
...
mService是个接口,public interface IWifiManager extends android.os.IInterface
public class WifiService extends IWifiManager.Stub
public static abstract class Stub extends android.os.Binder implements android.net.wifi.IWifiManager
这个mService是从哪里来的?
在ApplicationContext:
IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
越往下看越复杂,反正知道mService就是上面分析的WifiService 。
这个wifiManager将大部分的操作都转交给WifiService了。
在做个小总结,我们可以通过wifiManager来间接调用wifiService的服务,应用调用的wifiManager的方法来控制wifi网卡状态,
接下来我们看,从wifiService什么往下调用的:以Scan为例
wifiManager.Scan
-->return mService.startScan(false);
--> return WifiNative.scanCommand(forceActive);
我们到wifiNative去,发现所有函数都只声明,没有实现体。但发现每个函数都有个关键字native。其实就是
通过jni来调用c++下面的代码,想了解深入的在去找jni的资料。
通过搜索我们找到:
在android_net_wifi_Wifi.cpp frameworks\base\core\Jni 有
{ "scanCommand", "(Z)Z", (void*) android_net_wifi_scanCommand },
这个在一个结构体里,肯定是通过注册,与java层中的WifiNative 的方法联系起来。
现在这两个函数通过jni有关联了,调用 WifiNative.ScanCommand 就相当于调用 android_net_wifi_ScanCommand
我们发现这函数名也有规则,其实是可以随便取的。
不管它,往下看:
android_net_wifi_ScanCommand
| --> result = doBooleanCommand("SCAN", "OK");
android_net_wifi_Wifi.cpp <-- | -->if (doCommand(cmd, reply, sizeof(reply)) != 0)
| -->if (::wifi_command(cmd, replybuf, &reply_len) != 0)
wifi.c <--| --> return wifi_send_command(ctrl_conn, command, reply, reply_len);
| -->wifi_send_command
| -->ret = wpa_ctrl_request(ctrl, cmd, strlen(cmd), reply, reply_len, NULL);
wpa_supplicant <-- | -->if (send(ctrl->s, _cmd, _cmd_len, 0) < 0)
| --> return (ssize_t) sendto(socket, buf, buflen, flags, NULL, 0);
| --> return __socketcall( SYS_SENDTO, t );
在往下就是驱动了。
那么之前那个疑问又来了?谁给wifiService发Message呢?
我们在跟一下wifi网卡使能。
从wifiManager开始
-->public boolean setWifiEnabled(boolean enabled) {
--> return mService.setWifiEnabled(enabled);
--> sendEnableMessage(enable, true, Binder.getCallingUid());
-->Message msg = Message.obtain(mWifiHandler,
(enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
(persist ? 1 : 0), uid);
msg.sendToTarget();
看到没有,给自己发了Message。所以到这只能到handleMessage去找了。
setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
|--> if (!WifiNative.loadDriver())
| -->public native static boolean loadDriver();
| |jni|
| --> { "loadDriver", "()Z", (void *)android_net_wifi_loadDriver },
| --> return (jboolean)(::wifi_load_driver() == 0);
| wifi.c -->if (insmod( "/system/lib/modules/wlan.ko", "") < 0)这里我把宏替换掉了;
| 这里就加载完了驱动。
|但是这样wifi网卡还不得用,还要个 wpa_supplicant. 在setWifiEnabledBlocking中还发现:
|
| --> if (!WifiNative.startSupplicant())
--> public native static boolean startSupplicant();
--> { "startSupplicant", "()Z", (void *)android_net_wifi_startSupplicant },
--> return (jboolean)(::wifi_start_supplicant() == 0);
--> /*Check whether already running */
...
/* Before starting the daemon, make sure its config file exists */
...
/* Clear out any stale socket files that might be left over. */
要用到的确实挺多的。
static const char IFACE_DIR[] = "/data/system/wpa_supplicant";
static const char DRIVER_PROP_NAME[] = "wlan.driver.status";
static const char SUPPLICANT_NAME[] = "wpa_supplicant";
static const char SUPP_PROP_NAME[] = "init.svc.wpa_supplicant";
static const char SUPP_CONFIG_TEMPLATE[]= "/system/etc/wifi/wpa_supplicant.conf";
static const char SUPP_CONFIG_FILE[] = "/data/misc/wifi/wpa_supplicant.conf";
四、我们是从上层往底层是通了,那么从底层到上层呢,就是当我们启动wifi网卡成功后,要得通知应用层
使能wifi是否成功啊!
网上搜一下,有:
当wpa_supplicant 处理完SCAN 命令后,它会向控制通道发送事件通知扫描完成,从wifi_wait_for_event 函数会接收到该事件,由此
WifiMonitor 中的MonitorThread 会被执行来出来这个事件。
知道这样了我们再跟一下源码,看看是不是?
先搜源码 wifi_wait_for_event 看谁调用
{ "waitForEvent", "()Ljava/lang/String;", (void*) android_net_wifi_waitForEvent },
-->wifi_wait_for_event
-->result = wpa_ctrl_recv(monitor_conn, buf, &nread); (wifi.c)
-->res = recv(ctrl->s, reply, *reply_len, 0);
-->return recvfrom(socket, buf, buflen, flags, NULL, 0);
在wifiNative里有
/**
* Wait for the supplicant to send an event, returning the event string.
* @return the event string sent by the supplicant.
*/
public native static String waitForEvent();
现在知道了这函数就是在等待事件上报。
通过搜索发现:
在wifiMonitor类中 for (;;) {
String eventStr = WifiNative.waitForEvent();
...
}
我们在上面略微看了WifiStateTracker构造时发现(不记得的话就搜索,看谁创建它):
mWifiMonitor = new WifiMonitor(this);
1)分析wifiMonitor, 先看构造:
public WifiMonitor(WifiStateTracker tracker) {
mWifiStateTracker = tracker;
}
传的是WifiStateTracker,说明还得用到这个类。
明显的发现有个线程类class MonitorThread extends Thread {
public MonitorThread() {
super("WifiMonitor");
}
有现在就在本文件搜start,于是有:
public void startMonitoring() {
new MonitorThread().start();
}
看来是让人家调用的,我们搜一下,看谁调用:
在WifiStateTracker里面有两个方法:
public void startMonitoring() {
/*
* Get a handle on the WifiManager. This cannot be done in our
* constructor, because the Wifi service is not yet registered.
*/
mWM = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);
}
public void startEventLoop() {
mWifiMonitor.startMonitoring();
}
看注释应该是startEventLoop,谁又调用它?再搜:
发现了,在wifiService中的private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid)
mWifiStateTracker.startEventLoop();
细心点的话,会发现这个函数就是我们上面wifi使能的时候。从handleMessage中调用的,所以我们
只有我们使能后,才会去启动wifiMonitor的线程,然后去监听wpa_supplicant返回的事件。
这个线程是起来了, 这线程最重要的任务是String eventStr = WifiNative.waitForEvent(); 去查询监听
上报的事件。那事件来个呢,我猜应该也在这个run中做相应的处理吧!
确实:
handlePasswordKeyMayBeIncorrect();
handleSupplicantStateChange(eventData);
handleDriverEvent(eventData);
mWifiStateTracker.notifySupplicantLost();
handleEvent(event, eventData);
跟进去一些的话,这些handleXXX最终都是调用到 WifiStateTracker.notifyXXX,也就知道了
为什创建wifiMonitor时构造方法要用到 WifiStateTracker做参数。
源码大抵流程也跟得差不多了。