Android 7.1开机之后APN的加载及拨号上网流程分析

Posted 安时光Mrsongs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 7.1开机之后APN的加载及拨号上网流程分析相关的知识,希望对你有一定的参考价值。

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类图如下:

TelephonyProvider框架图

在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。

Android 7.1 DataConnection框架图

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();
        //[FEATURE]-Add-BEGIN by (songzhihao@paxsz.com) 2021/03/30 for network occour problem.
        SystemProperties.set(paxRestRadio, "120000");
        //[FEATURE]-Add-END by (songzhihao@paxsz.com) 2021/03/30 for network occour problem.
    }

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_

以上是关于Android 7.1开机之后APN的加载及拨号上网流程分析的主要内容,如果未能解决你的问题,请参考以下文章

Android APN的配置和加载

Android开发中页面启动时黑屏或者白屏的原因及解决办法

在 Android 9 上配置 APN(API 级别 28)

Android的开机流程

Android手机通过APN设置上网的方法

解决OpenWrt多拨刚开机拨号只拨上一次问题