一、功能简介
需求:开机自动开始搜网并显示网络列表
那么就不能将相关类做成单例,不能将subId、phoneId等卡相关的属性作为UI、服务的全局变量。
二、流程设计
NetworkSelectReceiver:监听开机广播,触发拉起搜网服务
NetworkOperatorService:搜网服务,完成后调起用户界面
NetworkOperatorList:网络模式列表,显示搜网结果
三、开发代码
(一)NetworkSelectReceiver
接收器配置 AndroidManifest.xml
<receiver
android:name=".settings.network.NetworkSelectReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SIM_STATE_CHANGED" />
</intent-filter>
</receiver>
内部逻辑
onReceive => checkAndUpdateKeyWhenFirstBoot => getNetworkSelectionModeForPhone
public class NetworkSelectReceiver extends BroadcastReceiver {
private Context mContext;
private SubscriptionManager mSubscriptionManager;
private static final int EVENT_GET_NETWORK_SELECTION_MODE_DONE = 300;
private static final String DATA_PHONE_ID = "phone_id";
private final static String TAG = "NetworkSelectReceiver ";
//1、监听开机广播
@Override
public void onReceive(Context context, Intent intent) {
mcontext = context;
if (TelephonyManager.getDefault().isMultiSimEnabled()) { //双卡设备
mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
List<SubscriptionInfo> mSubscriptionInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
int phoneCount = TelephonyManager.getDefault().getPhoneCount();
if (mSubscriptionInfoList == null) {
Log.d(TAG, "onReceive, no ActiveSubscriptionInfoList, phoneCount = " + phoneCount);
return ;
} else {
Log.d(TAG, "onReceive, mSubscriptionInfoList = " + mSubscriptionInfoList + ", phoneCount = " + phoneCount);
}
//遍历并操作每一张卡。
for (int i = 0; i < phoneCount; i++) {
if (SubscriptionManager.isValidPhoneId(i)) {
Log.d(TAG,"onReceive, isValidPhoneId = " + i);
checkAndUpdateKeyWhenFirstBoot(context, i);
}
}
} else {}//单卡逻辑
} //onReceive
//2、场景校验(根据需求添加)
private boolean checkAndUpdateKeyWhenFirstBoot(Context context, int phoneId) {
Log.d(TAG,"checkAndUpdateKeyWhenFirstBoot, phoneId = " + phoneId);
SharedPreferences prefs = ShowNetworkUtils.getSharedPreferences(context);
String simKey = NetworkUtils.KEY_FIRST_BOOT + phoneId;
//没有用到卡信息,此处用于debug,确认双卡是否正常
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String mccmnc = "";
if (tm == null) {
return false;
} else {
mccmnc = tm.getSimOperatorNumericForPhone(phoneId);
}
int simState = tm.getSimState(phoneId);
Log.d(TAG,"checkAndUpdateKeyWhenFirstBoot, simState = " + simState + ", mccmnc =" + mccmnc);
//卡没加载好以及飞行模式下不发起搜网
boolean isEnabled = (Settings.Glob