当前位置: 首页 > 工具软件 > apn-proxy > 使用案例 >

Android 7.0 APN 拨号上网流程分析

穆乐逸
2023-12-01

1、前言

在前段时间的项目中遇到客户的设备出现APN断开的情况没有自动连接,后来折腾了一段时间解决了这个问题。现在用这篇博客记录一下APN的选择和连接流程。

2、名词解析

APN:APN指一种网络接入技术,是通过手机上网时必须配置的一个参数,它决定了手机通过哪种接入方式来访问网络。
对于手机用户来说,可以访问的外部网络类型有很多,例如:Internet、WAP网站、集团企业内部网络、行业内部专用网络。而不同的接入点所能访问的范围以及接入的方式是不同的,网络侧如何知道手机激活以后要访问哪个网络从而分配哪个网段的IP呢,这就要靠APN来区分了,即APN决定了用户的手机通过哪种接入方式来访问什么样的网络。

PDN:Packet data network,分组数据网,即常说的Internet,在GPRS网络中代表外部数据网络的总称

3、Android 中APN的存储形式

Android 系统中APN是以apns-conf.xml文件的形式配置的,位于设备中的system/etc目录下。
apn 的配置信息如下:

  <apn carrier="ENTEL4G" //运营商
      mcc="736" //Mobile Country Code,移动国家码
      mnc="02"  //Mobile Network Code,移动网络码
      apn="4g.entel" //apn名称
      user=""
      password=""
      proxy="" //代理在这里插入代码片
      port=""  //端口
      authtype="2"
      type="default,supl" //apn类型
  />

4、初识TelephonyProvider

4.1 apn文件是怎么被解析的呢,设置中的apn信息怎么保存的呢,这里就轮到TelephonyProvider 出场了

TelephonyProvider继承自ContentProvider,在android中的代码路径为:
packages/providers/TelephonyProvider。

它的UML类图如下:

在AndroidManifest.xml中可以看到application 标签中定义了android:process=“com.android.phone” ,这样TelephonyProvider就运行在com.android.phone进程中,也就是packages\services\Telephony 目录下的Telephony服务。

4.2 TelephonyProvider 的onCreate()函数

代码如下:
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());

    // Call getReadableDatabase() to make sure onUpgrade is called
    if (VDBG) log("onCreate: calling getReadableDatabase to trigger onUpgrade");
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    // Update APN db on build update
    String newBuildId = SystemProperties.get("ro.build.id", null);
    if (!TextUtils.isEmpty(newBuildId)) {
        // Check if build id has changed
        SharedPreferences sp = getContext().getSharedPreferences(BUILD_ID_FILE,
                Context.MODE_PRIVATE);
        String oldBuildId = sp.getString(RO_BUILD_ID, "");
        if (!newBuildId.equals(oldBuildId)) {
            if (DBG) log("onCreate: build id changed from " + oldBuildId + " to " +
                    newBuildId);

            // Get rid of old preferred apn shared preferences
            SubscriptionManager sm = SubscriptionManager.from(getContext());
            if (sm != null) {
                List<SubscriptionInfo> subInfoList = sm.getAllSubscriptionInfoList();
                for (SubscriptionInfo subInfo : subInfoList) {
                    SharedPreferences spPrefFile = getContext().getSharedPreferences(
                            PREF_FILE_APN + subInfo.getSubscriptionId(), Context.MODE_PRIVATE);
                    if (spPrefFile != null) {
                        SharedPreferences.Editor editor = spPrefFile.edit();
                        editor.clear();
                        editor.apply();
                    }
                }
            }

            // Update APN DB
            updateApnDb();
        } else {
            if (VDBG) log("onCreate: build id did not change: " + oldBuildId);
        }
        sp.edit().putString(RO_BUILD_ID, newBuildId).apply();
    } else {
        if (VDBG) log("onCreate: newBuildId is empty");
    }

    if (VDBG) log("onCreate:- ret true");
    return true;
}

从上面的代码,我们知道TelephonyProvider初始化时的主要工作包括:

  1. new DatabaseHelper 创建出数据库;
  2. 根据build_id的值,如果跟之前的不同则重新load apn xml文件写入到数据库中,并将之前选中的sharepreference记录选中的 apn清除,并且最后将数据中不在apn xml文件中的数据行全部删除。

4.3 TelephonyProvider 的内部类 DatabaseHelper

DatabaseHelper是 TelephonyProvider 的一个内部类,在TelephonyProvider 的onCreate函数中首先被创建。

4.3.1 DatabaseHelper的构造函数中会传入数据的名字用于创建数据库,这个DATABASE_NAME 就是"telephony.db",创建路径位于:/data/user_de/0/com.android.providers.telephony/
databases/telephony.db
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, getVersion(context));
mContext = context;
}

4.3.2 DatabaseHelper 的onCreate函数
@Override
public void onCreate(SQLiteDatabase db) {
if (DBG) log(“dbh.onCreate:+ db=” + db);
createSimInfoTable(db);
createCarriersTable(db, CARRIERS_TABLE);
initDatabase(db);
if (DBG) log(“dbh.onCreate:- db=” + db);
}

这里可以看到它作了三件事:
1、创建SIM卡信息的表
2、创建运营商信息的表
3、初始化数据库,这里是重点。

4.3.2 DatabaseHelper 的 initDatabase()初始化作了哪些事

从这个代码中可以看到函数中主要是:
1、使用XML 解析apn-conf.xml文件并写入到数据库中。
2、将数据库中不是xml中的数据清除掉

    private void initDatabase(SQLiteDatabase db) {
        if (VDBG) log("dbh.initDatabase:+ db=" + db);
        // Read internal APNS data
        Resources r = mContext.getResources();
        XmlResourceParser parser = r.getXml(com.android.internal.R.xml.apns);
        int publicversion = -1;
        try {
            XmlUtils.beginDocument(parser, "apns");
            publicversion = Integer.parseInt(parser.getAttributeValue(null, "version"));
            loadApns(db, parser);
        } catch (Exception e) {
            loge("Got exception while loading APN database." + e);
        } finally {
            parser.close();
        }

        // Read external APNS data (partner-provided)
        XmlPullParser confparser = null;
        File confFile = getApnConfFile();

        FileReader confreader = null;
        if (DBG) log("confFile = " + confFile);
        try {
            confreader = new FileReader(confFile);
            confparser = Xml.newPullParser();
            confparser.setInput(confreader);
            XmlUtils.beginDocument(confparser, "apns");

            // Sanity check. Force internal version and confidential versions to agree
            int confversion = Integer.parseInt(confparser.getAttributeValue(null, "version"));
            if (publicversion != confversion) {
                log("initDatabase: throwing exception due to version mismatch");
                throw new IllegalStateException("Internal APNS file version doesn't match "
                        + confFile.getAbsolutePath());
            }

            loadApns(db, confparser);
        } catch (FileNotFoundException e) {
            // It's ok if the file isn't found. It means there isn't a confidential file
            // Log.e(TAG, "File not found: '" + confFile.getAbsolutePath() + "'");
        } catch (Exception e) {
            loge("initDatabase: Exception while parsing '" + confFile.getAbsolutePath() + "'" +
                    e);
        } finally {
            // Get rid of user/carrier deleted entries that are not present in apn xml file.
            // Those entries have edited value USER_DELETED/CARRIER_DELETED.
            if (VDBG) {
                log("initDatabase: deleting USER_DELETED and replacing "
                        + "DELETED_BUT_PRESENT_IN_XML with DELETED");
            }

            // Delete USER_DELETED
            db.delete(CARRIERS_TABLE, IS_USER_DELETED + " or " + IS_CARRIER_DELETED, null);

            // Change USER_DELETED_BUT_PRESENT_IN_XML to USER_DELETED
            ContentValues cv = new ContentValues();
            cv.put(EDITED, USER_DELETED);
            db.update(CARRIERS_TABLE, cv, IS_USER_DELETED_BUT_PRESENT_IN_XML, null);

            // Change CARRIER_DELETED_BUT_PRESENT_IN_XML to CARRIER_DELETED
            cv = new ContentValues();
            cv.put(EDITED, CARRIER_DELETED);
            db.update(CARRIERS_TABLE, cv, IS_CARRIER_DELETED_BUT_PRESENT_IN_XML, null);

            if (confreader != null) {
                try {
                    confreader.close();
                } catch (IOException e) {
                    // do nothing
                }
            }

            // Update the stored checksum
            setApnConfChecksum(getChecksum(confFile));
        }
        if (VDBG) log("dbh.initDatabase:- db=" + db);

    }

apn的xml 有那些呢 ?根据getApnConfFile 函数可以知道有如下这些目录。
private File getApnConfFile() {
// Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or “/system”.
File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH);
File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH);
File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH);
confFile = getNewerFile(confFile, oemConfFile);
confFile = getNewerFile(confFile, updatedConfFile);
return confFile;
}

private static final String PARTNER_APNS_PATH = “etc/apns-conf.xml”;
private static final String OEM_APNS_PATH = “telephony/apns-conf.xml”;
private static final String OTA_UPDATED_APNS_PATH = “misc/apns-conf.xml”;
private static final String OLD_APNS_PATH = “etc/old-apns-conf.xml”;

到这里TelephonyProvider的业务就很清晰了,他就要就是开机的时候会根据build id来判断是否试正常开机还是升级之后的不同版本,如果不同,则重新创建telephony.db数据库,并重新解析加载apn.xml文件写入到数库中。

5、开机之后APN界面是怎么自动选择APN连接的呢 ?

刚开始我以为设置界面开机之后会默认选择一个已连接的APN的逻辑是在设置里面做的,看了一下设置ApnSettings.java相关的代码发现并没有如何选择apn去拨号的操作,
代码路径:packages\apps\Settings\src\com\android\settings\ApnSettings.java
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Activity activity = getActivity();
final int subId = activity.getIntent().getIntExtra(SUB_ID,
SubscriptionManager.INVALID_SUBSCRIPTION_ID);

    mMobileStateFilter = new IntentFilter(
            TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);

    setIfOnlyAvailableForAdmins(true);

    mSubscriptionInfo = SubscriptionManager.from(activity).getActiveSubscriptionInfo(subId);
    mUiccController = UiccController.getInstance();

    CarrierConfigManager configManager = (CarrierConfigManager)
            getSystemService(Context.CARRIER_CONFIG_SERVICE);
    PersistableBundle b = configManager.getConfig();
    mHideImsApn = b.getBoolean(CarrierConfigManager.KEY_HIDE_IMS_APN_BOOL);
    mAllowAddingApns = b.getBoolean(CarrierConfigManager.KEY_ALLOW_ADDING_APNS_BOOL);
    mUserManager = UserManager.get(activity);
}

如果不是上层应用自动拨号的,那就是底层自动选择的了 ?带着疑问我看了一下开机后的log打印流程发现了端倪:在DCTracker的log中发现DcTracker对象被创建后会注册监听RILD上报事件,当上报EVENT_DATA_CONNECTION_ATTACHED 就会创建apn列表并且获取preference apn 进行拨号,当然第一次没有设置是没有preference apn 的,这里就从 apn 列表中选择apn 进行拨号,按着这条线索继续看一下DCTracker 的代码逻辑吧。

6、DCTracker 登场

这里先放一张DCTracker 的相关类图,它是Telephony架构中监听SIM状态的状态变化和拨号的结果,类似于WifiTrakcker或者NetworkMonitor这样的角色。它是跟随着com.android.phone进程启动的时候创建的,不同类型phone 对应着一种DcTracker。

6.1 DcTracker的构造函数
代码路径:frameworks/opt/telephony/src/java/com/android/internal/telephony/dataconnection/DcTracker.java
构造函数很长,但是总结一下就主要干了这几件事:
1、初始化mUiccController 并注册监听SIM状态
2、registerForAllEvents() 注册监听事件。
3、监听数据库变化以及其他的一些初始化工作。
这里看看registerForAllEvents 监听事件。
//***** Constructor
public DcTracker(Phone phone) {
super();
mPhone = phone;

    if (DBG) log("DCT.constructor");

    mResolver = mPhone.getContext().getContentResolver();
    mUiccController = UiccController.getInstance();
    mUiccController.registerForIccChanged(this, DctConstants.EVENT_ICC_CHANGED, null);
    mAlarmManager =
            (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
    mCm = (ConnectivityManager) mPhone.getContext().getSystemService(
            Context.CONNECTIVITY_SERVICE);


    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(INTENT_DATA_STALL_ALARM);
    filter.addAction(INTENT_PROVISIONING_APN_ALARM);

    // TODO - redundent with update call below?
    mDataEnabledSettings.setUserDataEnabled(getDataEnabled());

    mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
    mAutoAttachOnCreation.set(sp.getBoolean(Phone.DATA_DISABLED_ON_BOOT_KEY, false));

    mSubscriptionManager = SubscriptionManager.from(mPhone.getContext());
    mSubscriptionManager.addOnSubscriptionsChangedListener(mOnSubscriptionsChangedListener);

    HandlerThread dcHandlerThread = new HandlerThread("DcHandlerThread");
    dcHandlerThread.start();
    Handler dcHandler = new Handler(dcHandlerThread.getLooper());
    mDcc = DcController.makeDcc(mPhone, this, dcHandler);
    mDcTesterFailBringUpAll = new DcTesterFailBringUpAll(mPhone, dcHandler);

    mDataConnectionTracker = this;
    registerForAllEvents();
    update();
    mApnObserver = new ApnChangeObserver();
    phone.getContext().getContentResolver().registerContentObserver(
            Telephony.Carriers.CONTENT_URI, true, mApnObserver);

    initApnContexts();

    for (ApnContext apnContext : mApnContexts.values()) {
        // Register the reconnect and restart actions.
        filter = new IntentFilter();
        filter.addAction(INTENT_RECONNECT_ALARM + '.' + apnContext.getApnType());
        mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
    }

    // Add Emergency APN to APN setting list by default to support EPDN in sim absent cases
    initEmergencyApnSetting();
    addEmergencyApnSetting();

    mProvisionActionName = "com.android.internal.telephony.PROVISION" + phone.getPhoneId();

    mSettingsObserver = new SettingsObserver(mPhone.getContext(), this);
    registerSettingsObserver();
}

6.2 registerForAllEvents监听事件

这里最重要的还是EVENT_DATA_CONNECTION_ATTACHED 表示modem 注网完成接下来进行拨号的状态。
private void registerForAllEvents() {
mPhone.mCi.registerForAvailable(this, DctConstants.EVENT_RADIO_AVAILABLE, null);
mPhone.mCi.registerForOffOrNotAvailable(this,
DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
mPhone.mCi.registerForDataNetworkStateChanged(this,
DctConstants.EVENT_DATA_STATE_CHANGED, null);
// Note, this is fragile - the Phone is now presenting a merged picture
// of PS (volte) & CS and by diving into its internals you’re just seeing
// the CS data. This works well for the purposes this is currently used for
// but that may not always be the case. Should probably be redesigned to
// accurately reflect what we’re really interested in (registerForCSVoiceCallEnded).
mPhone.getCallTracker().registerForVoiceCallEnded(this,
DctConstants.EVENT_VOICE_CALL_ENDED, null);
mPhone.getCallTracker().registerForVoiceCallStarted(this,
DctConstants.EVENT_VOICE_CALL_STARTED, null);
registerServiceStateTrackerEvents();
// SubscriptionManager.registerForDdsSwitch(this,
// DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS, null);
mPhone.mCi.registerForPcoData(this, DctConstants.EVENT_PCO_DATA_RECEIVED, null);
}

    public void registerServiceStateTrackerEvents() {
    mPhone.getServiceStateTracker().registerForDataConnectionAttached(this,
            DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null);
    mPhone.getServiceStateTracker().registerForDataConnectionDetached(this,
            DctConstants.EVENT_DATA_CONNECTION_DETACHED, null);
    mPhone.getServiceStateTracker().registerForDataRoamingOn(this,
            DctConstants.EVENT_ROAMING_ON, null);
    mPhone.getServiceStateTracker().registerForDataRoamingOff(this,
            DctConstants.EVENT_ROAMING_OFF, null);
    mPhone.getServiceStateTracker().registerForPsRestrictedEnabled(this,
            DctConstants.EVENT_PS_RESTRICT_ENABLED, null);
    mPhone.getServiceStateTracker().registerForPsRestrictedDisabled(this,
            DctConstants.EVENT_PS_RESTRICT_DISABLED, null);
    mPhone.getServiceStateTracker().registerForDataRegStateOrRatChanged(this,
            DctConstants.EVENT_DATA_RAT_CHANGED, null);
}

6.3 拨号前的准备工作setupDataOnConnectableApns

RILD注网成功之后会上报Attached 事件,也就是DcTracker监听到EVENT_DATA_CONNECTION_ATTACHED 事件之后会 执行onDataConnectionAttached
case DctConstants.EVENT_DATA_CONNECTION_ATTACHED:
onDataConnectionAttached();
break;

onDataConnectionAttached()函数做一些notify phone 的操作后会执行setupDataOnConnectableApns,这里就开始准备拨号工作了。

这里APN的类型可能有多种,进行遍历之后清除APN的连接状态。最后根据APN的状态判断如果当前APN的类型是isConnectable就开始调用trySetupData(apnContext, waitingApns)正式进入拨号流程了,因为调用setupDataOnConnectableApns时传入的参数是RetryFailures.ALWAYS,所以这里waitingApns 是null。
private void setupDataOnConnectableApns(String reason, RetryFailures retryFailures) {
if (VDBG) log("setupDataOnConnectableApns: " + reason);

    if (DBG && !VDBG) {
        StringBuilder sb = new StringBuilder(120);
        for (ApnContext apnContext : mPrioritySortedApnContexts) {
            sb.append(apnContext.getApnType());
            sb.append(":[state=");
            sb.append(apnContext.getState());
            sb.append(",enabled=");
            sb.append(apnContext.isEnabled());
            sb.append("] ");
        }
        log("setupDataOnConnectableApns: " + reason + " " + sb);
    }

    for (ApnContext apnContext : mPrioritySortedApnContexts) {
        ArrayList<ApnSetting> waitingApns = null;

        if (VDBG) log("setupDataOnConnectableApns: apnContext " + apnContext);

        if (apnContext.getState() == DctConstants.State.FAILED
                || apnContext.getState() == DctConstants.State.SCANNING) {
            if (retryFailures == RetryFailures.ALWAYS) {
                apnContext.releaseDataConnection(reason);
            } else if (apnContext.isConcurrentVoiceAndDataAllowed() == false &&
                    mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
                // RetryFailures.ONLY_ON_CHANGE - check if voice concurrency has changed
                apnContext.releaseDataConnection(reason);
            } else {
                // RetryFailures.ONLY_ON_CHANGE - check if the apns have changed
                int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
                ArrayList<ApnSetting> originalApns = apnContext.getWaitingApns();
                if (originalApns != null && originalApns.isEmpty() == false) {
                    waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
                    if (originalApns.size() != waitingApns.size() ||
                            originalApns.containsAll(waitingApns) == false) {
                        apnContext.releaseDataConnection(reason);
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        }
        if (apnContext.isConnectable()) {
            log("isConnectable() call trySetupData");
            apnContext.setReason(reason);
            trySetupData(apnContext, waitingApns);
        }
    }
}

6.4 、开始拨号工作trySetupData
trySetupData()函数主要做两件事
1、判断APN状态是DctConstants.State.IDLE 的时候调用buildWaitingApns 构建拨号APN列表 并通过apnContext.setWaitingApns(waitingApns)将waitingApns列表设置到apnContext 中。
2、调用setupData(apnContext, radioTech)使用apn进行拨号连接。
if (apnContext.getState() == DctConstants.State.IDLE) {
if (waitingApns == null) {
waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
}
if (waitingApns.isEmpty()) {
notifyNoData(DcFailCause.MISSING_UNKNOWN_APN, apnContext);
notifyOffApnsOfAvailability(apnContext.getReason());
String str = “trySetupData: X No APN found retValue=false”;
if (DBG) log(str);
apnContext.requestLog(str);
return false;
} else {
apnContext.setWaitingApns(waitingApns);
isReconnectedFinsh = false;
if (DBG) {
log (“trySetupData: Create from mAllApnSettings : "
+ apnListToString(mAllApnSettings)+” isReconnectedFinsh "+isReconnectedFinsh);
}
}
}

6.5、buildWaitingApns分析

buildWaitingApns函数新建的一个WaitingApns集合的APN来源有两个:
1、getPreferredApn()从文件存储中去获取之前选中过的APN,如果该APN 的Type类型为上网的类型并且numeric 国家码和SIM卡的国家码一致,就将此apn添加到apn拨号列表中,如果不同就清除保存的preferenceAPN为-1,这样可以防止换了SIM卡的情况。当然恢复出厂设置或者刷机第一次起来的时候这个preferenceAPN也是NULL的,因为没有设置过。

2、从mAllApnSettings 中遍历选中APN的type 为拨号相同type的APN 添加到拨号列表中,mAllApnSettings 自动从代码里面搜一下可以看到它是从数据库中搜索而来的,根据MMC国家码来判断如果和SIM卡相同就添加到mAllApnSettings 列表中,这样mAllApnSettings 列表中实际上是有很多不同type 比如上网,短信等等类型的apn。

/**
 * Build a list of APNs to be used to create PDP's.
 *
 * @param requestedApnType
 * @return waitingApns list to be used to create PDP
 *          error when waitingApns.isEmpty()
 */
private ArrayList<ApnSetting> buildWaitingApns(String requestedApnType, int radioTech) {
    if (DBG) log("buildWaitingApns: E requestedApnType=" + requestedApnType);
    ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>();

    if (requestedApnType.equals(PhoneConstants.APN_TYPE_DUN)) {
        ApnSetting dun = fetchDunApn();
        if (dun != null) {
            apnList.add(dun);
            if (DBG) log("buildWaitingApns: X added APN_TYPE_DUN apnList=" + apnList);
            return apnList;
        }
    }

    IccRecords r = mIccRecords.get();
    String operator = (r != null) ? r.getOperatorNumeric() : "";

    // This is a workaround for a bug (7305641) where we don't failover to other
    // suitable APNs if our preferred APN fails.  On prepaid ATT sims we need to
    // failover to a provisioning APN, but once we've used their default data
    // connection we are locked to it for life.  This change allows ATT devices
    // to say they don't want to use preferred at all.
    boolean usePreferred = true;
    try {
        usePreferred = ! mPhone.getContext().getResources().getBoolean(com.android.
                internal.R.bool.config_dontPreferApn);
    } catch (Resources.NotFoundException e) {
        if (DBG) log("buildWaitingApns: usePreferred NotFoundException set to true");
        usePreferred = true;
    }
    if (usePreferred) {
        //查询数据库看是否有志气设置的已经选中过的APN
        mPreferredApn = getPreferredApn();
    }
    if (DBG) {
        log("buildWaitingApns: usePreferred=" + usePreferred
                + " canSetPreferApn=" + mCanSetPreferApn
                + " mPreferredApn=" + mPreferredApn
                + " operator=" + operator + " radioTech=" + radioTech
                + " IccRecords r=" + r);
    }

    if (usePreferred && mCanSetPreferApn && mPreferredApn != null &&
            mPreferredApn.canHandleType(requestedApnType)) {
        if (DBG) {
            log("buildWaitingApns: Preferred APN:" + operator + ":"
                    + mPreferredApn.numeric + ":" + mPreferredApn);
        }
        if (mPreferredApn.numeric.equals(operator)) {
            if (ServiceState.bitmaskHasTech(mPreferredApn.bearerBitmask, radioTech)) {
                apnList.add(mPreferredApn);
                if (DBG) log("buildWaitingApns: X added preferred apnList=" + apnList);
                return apnList;
            } else {
                if (DBG) log("buildWaitingApns: no preferred APN");
                setPreferredApn(-1);
                mPreferredApn = null;
            }
        } else {
            if (DBG) log("buildWaitingApns: no preferred APN");
            setPreferredApn(-1);
            mPreferredApn = null;
        }
    }
    if (mAllApnSettings != null) {
        if (DBG) log("buildWaitingApns: mAllApnSettings=" + mAllApnSettings);
        for (ApnSetting apn : mAllApnSettings) {
            if (apn.canHandleType(requestedApnType)) {
                if (ServiceState.bitmaskHasTech(apn.bearerBitmask, radioTech)) {
                    if (DBG) log("buildWaitingApns: adding apn=" + apn);
                    apnList.add(apn);
                } else {
                    if (DBG) {
                        log("buildWaitingApns: bearerBitmask:" + apn.bearerBitmask + " does " +
                                "not include radioTech:" + radioTech);
                    }
                }
            } else if (DBG) {
                log("buildWaitingApns: couldn't handle requested ApnType="
                        + requestedApnType);
            }
        }
    } else {
        loge("mAllApnSettings is null!");
    }
    if (DBG) log("buildWaitingApns: " + apnList.size() + " APNs in the list: " + apnList);
    return apnList;
}

6.6 、apnContext.setWaitingApns(waitingApns)

setWaitingApns是RetryManager.java的一个方法,代码路径是:frameworks/opt/telephony/src/java/com/android/internal/telephony/RetryManager.java
设置apnContext的waitingApns 时会配置RetryManager的config 信息,debug 版本可以通过SystemProperties.get(“test.data_retry_config”)配置测试,我们这里用默认的SIM配置。包含apn重试最大次数,apn重试延迟时间等等,和获取当前重试apn列表的mCurrentApnIndex 索引,在每次设置setWaitingApns都会将这些config信息全部reset。这就意味着如果设置一次setWaitingApns,所有的重试策略都会重置,apn列表选择重新开始。这里其实是有点问题的,后面再说。

private void reset() {
    mMaxRetryCount = 0;
    mRetryCount = 0;
    mCurrentApnIndex = -1;
    mSameApnRetryCount = 0;
    mModemSuggestedDelay = NO_SUGGESTED_RETRY_DELAY;
    mRetryArray.clear();
}

6.7、setupData()拨号函数。

1、setupData拨号的时候首先通过apnSetting = apnContext.getNextApnSetting() 从apnContext中获取拨号列表中的apn。
2、这里有几种情况下会替换apnContext 中的apnSetting:
1>还有dataConnection没有断开,直接dcacApnSetting = dcac.getApnSettingSync()获取dcac的apnSetting 替换用来拨号
2> dcac断开的情况下,如果isOnlySingleDcAllowed或者isHigherPriorityApnContextActive ,就是如果是只允许单dcac模式或者有更高优先级的apnContext也是不用getNextApnSetting得到的apnSetting直接return返回停止拨号。
3>上述情况都不满足的情况下会cleanUpAllConnections断开 当前所以apnContext连接,如果是不是IDLE或者FAILED状态则表示cleanUpAllConnections没有完成清除,这种情况下也是直接return停止拨号操作。
3、以上判断走完后就会将当前的apnContext设置为参数通过EVENT_DATA_SETUP_COMPLETE 发送给RILD最终完成拨号。
Message msg = obtainMessage();
msg.what = DctConstants.EVENT_DATA_SETUP_COMPLETE;
msg.obj = new Pair<ApnContext, Integer>(apnContext, generation);
dcac.bringUp(apnContext, profileId, radioTech, msg, generation);

private boolean setupData(ApnContext apnContext, int radioTech) {
    if (DBG) log("setupData: apnContext=" + apnContext);
    apnContext.requestLog("setupData");
    ApnSetting apnSetting;
    DcAsyncChannel dcac = null;

    apnSetting = apnContext.getNextApnSetting();
    log("try this apnSetting:"+apnSetting);
    if (apnSetting == null) {
        if (DBG) log("setupData: return for no apn found!");
        return false;
    }

    int profileId = apnSetting.profileId;
    if (profileId == 0) {
        profileId = getApnProfileID(apnContext.getApnType());
    }

    // On CDMA, if we're explicitly asking for DUN, we need have
    // a dun-profiled connection so we can't share an existing one
    // On GSM/LTE we can share existing apn connections provided they support
    // this type.
    if (apnContext.getApnType() != PhoneConstants.APN_TYPE_DUN ||
            teardownForDun() == false) {
        dcac = checkForCompatibleConnectedApnContext(apnContext);
        if (dcac != null) {
            // Get the dcacApnSetting for the connection we want to share.
            ApnSetting dcacApnSetting = dcac.getApnSettingSync();
            if (dcacApnSetting != null) {
                // Setting is good, so use it.
                log("dcac still connect, dcac.getApnSettingSync():"+dcacApnSetting);
                apnSetting = dcacApnSetting;
            }
        }
    }
    if (dcac == null) {
        if (isOnlySingleDcAllowed(radioTech)) {
            if (isHigherPriorityApnContextActive(apnContext)) {
                if (DBG) {
                    log("setupData: Higher priority ApnContext active.  Ignoring call");
                }
                return false;
            }

            // Only lower priority calls left.  Disconnect them all in this single PDP case
            // so that we can bring up the requested higher priority call (once we receive
            // response for deactivate request for the calls we are about to disconnect
            if (cleanUpAllConnections(true, Phone.REASON_SINGLE_PDN_ARBITRATION)) {
                // If any call actually requested to be disconnected, means we can't
                // bring up this connection yet as we need to wait for those data calls
                // to be disconnected.
                if (DBG) log("setupData: Some calls are disconnecting first.  Wait and retry");
                return false;
            }

            // No other calls are active, so proceed
            if (DBG) log("setupData: Single pdp. Continue setting up data call.");
        }

        dcac = findFreeDataConnection();

        if (dcac == null) {
            dcac = createDataConnection();
        }

        if (dcac == null) {
            if (DBG) log("setupData: No free DataConnection and couldn't create one, WEIRD");
            return false;
        }
    }
    final int generation = apnContext.incAndGetConnectionGeneration();
    if (DBG) {
        log("setupData: dcac=" + dcac + " apnSetting=" + apnSetting + " gen#=" + generation);
    }

    apnContext.setDataConnectionAc(dcac);
    apnContext.setApnSetting(apnSetting);
    apnContext.setState(DctConstants.State.CONNECTING);
    mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());

    Message msg = obtainMessage();
    msg.what = DctConstants.EVENT_DATA_SETUP_COMPLETE;
    msg.obj = new Pair<ApnContext, Integer>(apnContext, generation);
    dcac.bringUp(apnContext, profileId, radioTech, msg, generation);

    if (DBG) log("setupData: initing!");
    return true;
}

private void setInitialAttachApn() {
    ApnSetting iaApnSetting = null;
    ApnSetting defaultApnSetting = null;
    ApnSetting firstApnSetting = null;

    log("setInitialApn: E mPreferredApn=" + mPreferredApn);

    if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
        firstApnSetting = mAllApnSettings.get(0);
        log("setInitialApn: firstApnSetting=" + firstApnSetting);

        // Search for Initial APN setting and the first apn that can handle default
        for (ApnSetting apn : mAllApnSettings) {
            // Can't use apn.canHandleType(), as that returns true for APNs that have no type.
            if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_IA) &&
                    apn.carrierEnabled) {
                // The Initial Attach APN is highest priority so use it if there is one
                log("setInitialApn: iaApnSetting=" + apn);
                iaApnSetting = apn;
                break;
            } else if ((defaultApnSetting == null)
                    && (apn.canHandleType(PhoneConstants.APN_TYPE_DEFAULT))) {
                // Use the first default apn if no better choice
                log("setInitialApn: defaultApnSetting=" + apn);
                defaultApnSetting = apn;
            }
        }
    }

    // The priority of apn candidates from highest to lowest is:
    //   1) APN_TYPE_IA (Initial Attach)
    //   2) mPreferredApn, i.e. the current preferred apn
    //   3) The first apn that than handle APN_TYPE_DEFAULT
    //   4) The first APN we can find.

    ApnSetting initialAttachApnSetting = null;
    if (iaApnSetting != null) {
        if (DBG) log("setInitialAttachApn: using iaApnSetting");
        initialAttachApnSetting = iaApnSetting;
    } else if (mPreferredApn != null) {
        if (DBG) log("setInitialAttachApn: using mPreferredApn");
        initialAttachApnSetting = mPreferredApn;
    } else if (defaultApnSetting != null) {
        if (DBG) log("setInitialAttachApn: using defaultApnSetting");
        initialAttachApnSetting = defaultApnSetting;
    } else if (firstApnSetting != null) {
        if (DBG) log("setInitialAttachApn: using firstApnSetting");
        initialAttachApnSetting = firstApnSetting;
    }

    if (initialAttachApnSetting == null) {
        if (DBG) log("setInitialAttachApn: X There in no available apn");
    } else {
        if (DBG) log("setInitialAttachApn: X selected Apn=" + initialAttachApnSetting);

        mPhone.mCi.setInitialAttachApn(initialAttachApnSetting.apn,
                initialAttachApnSetting.protocol, initialAttachApnSetting.authType,
                initialAttachApnSetting.user, initialAttachApnSetting.password, null);
    }
}

7、拨号完成,4G网络可以正常使用

framework拨号设置完成以后,RILD开始拨号分配ip 这些链路信息成功后会返回给DataConnection EVENT_SETUP_DATA_CONNECTION_DONE事件,同时DataConnection更新自己的networkAgent通知ConnectivityService改变网络状态为Connected,到这里整个拨号流程就全部结束了.

代码路径:frameworks/opt/telephony/src/java/com/android/internal/telephony/dataconnection/DataConnection.java
private class DcActivatingState extends State {
@Override
public boolean processMessage(Message msg) {
boolean retVal;
AsyncResult ar;
ConnectionParams cp;

        if (DBG) log("DcActivatingState: msg=" + msgToString(msg));
        switch (msg.what) {
            case EVENT_DATA_CONNECTION_DRS_OR_RAT_CHANGED:
            case EVENT_CONNECT:
                // Activating can't process until we're done.
                deferMessage(msg);
                retVal = HANDLED;
                break;

            case EVENT_SETUP_DATA_CONNECTION_DONE:
                ar = (AsyncResult) msg.obj;
                cp = (ConnectionParams) ar.userObj;

                DataCallResponse.SetupResult result = onSetupConnectionCompleted(ar);
                if (result != DataCallResponse.SetupResult.ERR_Stale) {
                    if (mConnectionParams != cp) {
                        loge("DcActivatingState: WEIRD mConnectionsParams:"+ mConnectionParams
                                + " != cp:" + cp);
                    }
                }
                if (DBG) {
                    log("DcActivatingState onSetupConnectionCompleted result=" + result
                            + " dc=" + DataConnection.this);
                }
                if (cp.mApnContext != null) {
                    cp.mApnContext.requestLog("onSetupConnectionCompleted result=" + result);
                }

5、结尾

6.6和6.7中提到的拨号的问题:

我们看一下6.6中 trySetupData 函数里面判断只要是当前apnContext状态为DctConstants.State.IDLE就会去 buildWaitingApns并且设置到apnContext 中,前面我们也提到
apnContext中每次设置setWaitingApns的时候都会重置currentApnSettingIndex脚本,这样每次重试的时候都是重头开始去apn拨号,而且6.7中有很多种情况会替换到从apnContext中取到的apnSetting,比如当前dcac没有断开连接,当前连接正在断开等等状态都会导致拨号跳过,好家伙,这么坑的漏洞就导致客户那边出现的每次拨号都是使用第一个APN拨号,列表的其他apn没有用到,因为都跳过了,导致拨号一直失败,自然设置界面的apn列表当然没有apn被连接上。

这个问题的解决办法就是尽量不要多次调用apnContext.setWaitingApns防止RetryManager的config参数被重置,另外setUpData拨号函数里面如果retrun跳过当前apn的话记录currentIndex这样下次还是使用这个apn拨号,这样就可以保证apn列表循环尝试了。
if (apnContext.getState() == DctConstants.State.IDLE) {
if (waitingApns == null) {
waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
}
if (waitingApns.isEmpty()) {
notifyNoData(DcFailCause.MISSING_UNKNOWN_APN, apnContext);
notifyOffApnsOfAvailability(apnContext.getReason());
String str = “trySetupData: X No APN found retValue=false”;
if (DBG) log(str);
apnContext.requestLog(str);
return false;
} else {
apnContext.setWaitingApns(waitingApns);
}

 类似资料: