android双卡时对apn的操作

apn(access point names),每个卡都会对应一系列的apn,如主卡为联通卡,对应的apn有3gwap/3gnet/uninet/nuiwap/3gwap等。每个卡默认选择一个apn,用户可更改。

1. 获取主卡或副卡当前使用的apn,对应的uri地址:"content://telephony/carriers/preferapn"。

    APN getAPN(int subId)
        Uri PREFERAPN_URI = Uri.parse("content://telephony/carriers/preferapn");
        uri = Uri.withAppendedPath(PREFERAPN_URI, "/subId/" + subId);

slotId和subId:可以根据卡槽的slotId得到subId:

    int subId = MtkSubscriptionManager.getSubIdUsingPhoneId(slotId);

2. 获取主卡或副卡所有的apn列表,对应的uri地址:"content://telephony/carriers"。

    List<APN> getApnList(int subId)//某个卡槽对应的APN列表
        uri = Uri.parse("content://telephony/carriers");
        String mccmnc = mTelephonyManager.getSimOperator(subId);//where条件根据mccmnc得到
        //主副卡,可根据current来区分,"current = 1",表示在使用的sim卡,即主卡。"current = 0",为副卡。

3. 针对某个卡增加apn

     boolean addApn(APN newApn)
        uri = Uri.parse("content://telephony/carriers");

4. 更新或删除某个卡的某一apn
    boolean update(APN apn)

    boolean update(APN apn)
    boolean removeAPN(APN apn)
        int pos = Integer.parseInt(apn.apnkey);    
        mUri = Uri.parse("content://telephony/carriers");
        uri = ContentUris.withAppendedId(mUri, pos);

5. 恢复apn到默认状态  

 boolean restoreDefaultApn(int subId) //把某个卡槽对应的APN恢复到默认值
        Uri DEFAULTAPN_URI = Uri.parse("content://telephony/carriers/restore");
        uri = Uri.withAppendedPath(DEFAULTAPN_URI, "/subId/" + subId);

    若是插入双卡,只要一个卡执行该功能,两个卡的apn都会恢复到初始值。

6. 代码如下

public class MyAPNManager {
	private static final String TAG = "MyAPNManager";
	private static final boolean DEBUG = true;


    public static final String RESTORE_CARRIERS_URI = "content://telephony/carriers/restore";
    public static final String PREFERRED_APN_URI = "content://telephony/carriers/preferapn";
    private static final Uri DEFAULTAPN_URI = Uri.parse(RESTORE_CARRIERS_URI);
    private static final Uri PREFERAPN_URI = Uri.parse(PREFERRED_APN_URI);
	/**
	 * Standard projection for the interesting columns of a normal note.
	 */
	private static final String[] PROJECTION = new String[] { 
			Telephony.Carriers._ID, // 0
			Telephony.Carriers.NAME, 
			Telephony.Carriers.APN, 
			Telephony.Carriers.PROXY, 
			Telephony.Carriers.PORT, 
			Telephony.Carriers.USER, // 5
			Telephony.Carriers.PASSWORD,
			Telephony.Carriers.SERVER, 
			Telephony.Carriers.MMSC, 
			Telephony.Carriers.MMSPROXY,
			Telephony.Carriers.MMSPORT, //10 
			Telephony.Carriers.MCC, 
			Telephony.Carriers.MNC, 
			Telephony.Carriers.AUTH_TYPE, 
			Telephony.Carriers.TYPE,//type
			Telephony.Carriers.PROTOCOL,//15
			Telephony.Carriers.ROAMING_PROTOCOL,  
			Telephony.Carriers.CARRIER_ENABLED, 
			Telephony.Carriers.BEARER,
			Telephony.Carriers.MVNO_TYPE,
			Telephony.Carriers.MVNO_MATCH_DATA,//20
			Telephony.Carriers.USER_VISIBLE
			//Telephony.Carriers.NUMERIC, 
			//Telephony.Carriers.CURRENT
	};

	protected TelephonyManager mTelephonyManager;
	private int mSlotId;
	protected Uri mUri;
	private Context mContext;
	private SubscriptionManager mSubscrMgr;
	//private SubscriptionInfo mSubscriptionInfo;
	private int mSubId, mSubId1;
	private ContentResolver mResolver;
	private SubscriptionInfo subscriptionInfo;
        private int mSlotCnt = 0;//the count of Slot

	public MyAPNManager(Context context) {
		debug("enter MyAPNManager()");
		mContext = context;
		mSlotId = 0;//single sim card

		mTelephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		mSubscrMgr = SubscriptionManager.from(mContext);
		mResolver = mContext.getContentResolver();
		mSlotCnt = mTelephonyManager.getSimCount();//get the count of Slot

		debug("mSlotCnt = " + mSlotCnt);
		//mSubscriptionInfo = SubscriptionManager.from(activity).getActiveSubscriptionInfo(subId);
		//mSubscriptionInfo = mSubscrMgr.getActiveSubscriptionInfoForSimSlotIndex(soltId);	
		mSubId = getSubIdBySlotId(mSlotId);
		mSubId1 = getSubIdBySlotId(1);
		int subId = MtkSubscriptionManager.getSubIdUsingPhoneId(0);
		int subId1 = MtkSubscriptionManager.getSubIdUsingPhoneId(1);
		debug("mSubId = " + mSubId + ", mSubId1 = " + mSubId1 + ", subId = " + subId + ", subId1 = " + subId1);

 		mUri = Telephony.Carriers.CONTENT_URI;
	}

	private int getSubIdBySlotId(int slotId){
		debug("enter getSubIdBySlotId()");
		int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
		
		subscriptionInfo = mSubscrMgr.getActiveSubscriptionInfoForSimSlotIndex(slotId);
		debug("slotId=" + slotId + ", subscriptionInfo = " + subscriptionInfo);

		if(null != subscriptionInfo){		
			subId = subscriptionInfo.getSubscriptionId();	
		}
		debug("subId = " + subId);
		return subId;
	}


	/* 2.1 get current apn begin */
	public APN getAPN(int slotId){
		int subId = MtkSubscriptionManager.getSubIdUsingPhoneId(slotId);
		debug("enter getAPN() subId = " + subId);

		APN myApn = null;
		Cursor cursor = null;
		try{
			cursor = mResolver.query(getPreferApnUri(subId), PROJECTION,
				        null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
			debug("cursor = " + cursor + " : " + cursor.getCount());

		    if (cursor.getCount() > 0) {//if (cur != null && cur.moveToFirst())
		        cursor.moveToFirst();

				myApn = new APN(cursor.getString(0), cursor.getString(1), cursor.getString(2), 
								cursor.getString(3), cursor.getString(4), cursor.getString(5),
								cursor.getString(6), cursor.getString(7), cursor.getString(8), 
								cursor.getString(9), cursor.getString(10), cursor.getString(11), 
								cursor.getString(12), cursor.getInt(13), cursor.getString(14),
						 		cursor.getString(15), cursor.getString(16), cursor.getInt(17), 
								cursor.getString(18), cursor.getString(19), cursor.getString(20),
								cursor.getInt(21));
		    }
		    debug("myApn = " + myApn);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			if(cursor!=null)
			cursor.close();
		}
        return myApn;
	}

    private Uri getPreferApnUri(int subId) {
        Uri preferredUri = Uri.withAppendedPath(PREFERAPN_URI, "/subId/" + subId);
        debug("getPreferredApnUri: " + preferredUri);
        return preferredUri;
    }
	/* 2.1 get current apn end */
	
	/* 2.2 get list of apn begin */
	private String getWhere(int subId){
		debug("enter getWhere()");
        String mccmnc = mTelephonyManager.getSimOperator(subId);
        debug("mccmnc = " + mccmnc);

        String where = "numeric=\"" + mccmnc + "\""; 
        where += " AND NOT (type='ia' AND (apn=\"\" OR apn IS NULL)) AND user_visible!=0";
        //debug("1 where: " + where);	

        /// M: for VoLTE, do not show ims apn for non-VoLTE project 
        if (!FeatureOption.MTK_VOLTE_SUPPORT) {
            where += " AND NOT (type='ims' OR type='ia,ims')";
	        //debug("2 where: " + where);					
        }

        debug("where: " + where);
		return where;		
	}

    private boolean shouldSkipApn(String type) {
    	boolean isSkipApn = "cmmail".equals(type);
		debug("isSkipApn = " + isSkipApn);
		return isSkipApn;
        //return "cmmail".equals(type);
    }

	public List<APN> getApnList(int slotId){
		int subId = MtkSubscriptionManager.getSubIdUsingPhoneId(slotId);
		debug("enter getApnList() subId = " + subId + ", mUri = " + mUri);

		List<APN> apnList = new ArrayList<APN>();
		APN apnInfo = null;
		//String projection[] = {"_id", "name", "apn", "type", "current", "mcc", "mnc", "carrier_enabled", "mvno_type", "mvno_match_data"}; 
		String where = getWhere(subId);
		Cursor cursor = null;
		try{
		    cursor = mResolver.query(
		            mUri,//Telephony.Carriers.CONTENT_URI, 
					PROJECTION,
					where.toString(),
					null, 
					Telephony.Carriers.DEFAULT_SORT_ORDER);
			debug("cursor = " + cursor + " : " + cursor.getCount());

			if(null != cursor){	

				int pid = android.os.Process.myPid();  
				String procName = null;
				ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);  
				for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {  
					if (appProcess.pid == pid) {  
						procName = appProcess.processName;  
					}  
				}  
				debug("procName = " + procName + ", pid = " + pid);

				while(cursor.moveToNext()){
					String type = cursor.getString(14);//"type"
					String mvnoType = cursor.getString(19);
                	String mvnoMatchData = cursor.getString(20);

		            if(shouldSkipApn(type)) {
						//debug("will move next");
		                cursor.moveToNext();
		                continue;
		            }	
					if (!TextUtils.isEmpty(mvnoType) && !TextUtils.isEmpty(mvnoMatchData)) {
						//mvnoList -- 虚拟运营商 --只要是虚拟运营商都不会显示?
					} else {
						//mnoList -- MVNO(Mobile Virtaul Network Operator)虚拟网络运营商,没有自己的实体网络,通过租用MNO(Mobile Network Operator)的网络来提供网络服务。
						apnInfo = new APN(cursor.getString(0), cursor.getString(1), cursor.getString(2), 
									cursor.getString(3), cursor.getString(4), cursor.getString(5),
									cursor.getString(6), cursor.getString(7), cursor.getString(8), 
									cursor.getString(9), cursor.getString(10), cursor.getString(11), 
									cursor.getString(12), cursor.getInt(13), cursor.getString(14),
							 		cursor.getString(15), cursor.getString(16), cursor.getInt(17), 
									cursor.getString(18), cursor.getString(19), cursor.getString(20),
									cursor.getInt(21));
						//debug("apnInfo = " + apnInfo);			
						apnList.add(apnInfo);
					}
				}
			}
		    debug("apnList = " + apnList);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			if(cursor!=null)
			cursor.close();
		}
        return apnList;
	}
	/* 2.2 get list of apn end */


	/* 2.3 update apn begin */
	public boolean updateApn(APN newApn, boolean force) {//'mSlotId' is not used
		debug("force = " + force + ", newApn = " + newApn);
		return update(mContext, force, /*mSlotId,*/ newApn.getKey(), 
			newApn.getName(), newApn.getApn(), newApn.getProxy(), 
			newApn.getPort(), newApn.getUser(), newApn.getPassword(),
			newApn.getServer(), newApn.getMmsc(), newApn.getMmsproxy(), 
			newApn.getMmsport(), newApn.getMcc(), newApn.getMnc(), 
			newApn.getAuthTypeVal(), newApn.getApnType(), newApn.getApnProtocol(), 
			newApn.getRoamingProtocol(), newApn.getCarrierEnabled(),
			newApn.getBearerVal());
	}

	public boolean update(Context context, boolean force, /*int slotId,*/
			String apnkey, String name, String apn, String proxy,
			String port, String user, String password, String server,
			String mmsc, String mmsproxy, String mmsport, String mcc, 
			String mnc, int authTypeVal, String strType, String protocol, 
			String roamingProtocol, int carrierEnabled, String bearerVal) {
		int pos = Integer.parseInt(apnkey);		
		Uri uri = ContentUris.withAppendedId(mUri, pos);
		debug("apnkey = " + apnkey + ", pos = " + pos + ", mUri = " + mUri + ", uri = " + uri);

		if (!force
				&& (name.length() < 1 || apn.length() < 1 || mcc.length() != 3 || (mnc
						.length() & 0xFFFE) != 2)) {
			return false;
		}

		ContentValues values = new ContentValues();

		values.put(Telephony.Carriers.NAME, name);
		values.put(Telephony.Carriers.APN, apn);
		values.put(Telephony.Carriers.PROXY, checkNotSet(proxy));
		values.put(Telephony.Carriers.PORT, checkNotSet(port));
		values.put(Telephony.Carriers.USER, checkNotSet(user));
		values.put(Telephony.Carriers.PASSWORD, checkNotSet(password));
		values.put(Telephony.Carriers.SERVER, checkNotSet(server));
		values.put(Telephony.Carriers.MMSC, checkNotSet(mmsc));
		values.put(Telephony.Carriers.MMSPROXY, checkNotSet(mmsproxy));
		values.put(Telephony.Carriers.MMSPORT, checkNotSet(mmsport));

		values.put(Telephony.Carriers.AUTH_TYPE, authTypeVal);
		values.put(Telephony.Carriers.TYPE, checkNotSet(strType));
		values.put(Telephony.Carriers.PROTOCOL, checkNotSet(protocol));
		values.put(Telephony.Carriers.ROAMING_PROTOCOL, checkNotSet(roamingProtocol));
		values.put(Telephony.Carriers.CARRIER_ENABLED, carrierEnabled);

		values.put(Telephony.Carriers.MCC, mcc);
		values.put(Telephony.Carriers.MNC, mnc);
		values.put(Telephony.Carriers.NUMERIC, mcc + mnc);
		debug("values = " + values);

		String numeric = SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC);
		debug("numeric = " + numeric);		

		String curMnc = null;
		String curMcc = null;
		// MCC is first 3 chars and then in 2 - 3 chars of MNC
		if (numeric != null && numeric.length() > 4) {
			// Country code
			curMcc = numeric.substring(0, 3);
			// Network code
			curMnc = numeric.substring(3);
			debug("curMcc = " + curMcc + ", curMnc = " + curMnc);
		}
		if (curMnc != null && curMcc != null) {
			if (curMnc.equals(mnc) && curMcc.equals(mcc)) {
				values.put(Telephony.Carriers.CURRENT, 1);
			}
		}

		if (bearerVal != null) {
			values.put(Telephony.Carriers.BEARER, Integer.parseInt(bearerVal));
		}

        values.put(MtkTelephony.Carriers.SOURCE_TYPE, 1);

		int count = 0;
		if (uri != null) {
			count = context.getContentResolver()
					.update(uri, values, null, null);
		}
		return count > 0 ? true : false;
	}

	private String checkNotSet(String value) {
		return value == null ?  "" : value;
	}
	/* 2.3 update apn end */


	/* 2.4 remove apn begin */
	/**
	 * Remove a APN for specific key.
	 * @param apnKey key of apn
	 * @return true if the apn was deleted
	 */
	public boolean removeAPN(String apnKey) {
		debug("enter removeAPN()"); 

		int pos = Integer.parseInt(apnKey);
		Uri uri = ContentUris.withAppendedId(mUri, pos);
		debug("apnKey-->" + apnKey +", uri--->" + uri);
		int count = 0;
		if (uri != null) {
			count = mContext.getContentResolver().delete(uri, null, null);
		}
		return count > 0 ? true : false;
	}

	/* 2.4 remove apn end */

	/* 2.5 restore to defualt begin */
	public boolean restoreDefaultApn() {
        debug("enter restoreDefaultApn()");
		SubscriptionInfo subInfo = null;
        for (int i = 0; i < mSlotCnt; ++i) {
            subInfo = mSubscrMgr.getActiveSubscriptionInfoForSimSlotIndex(i);
			debug(i + " : " + subInfo);
            if (subInfo != null) {
				int subId = subInfo.getSubscriptionId();
		        mResolver.delete(getDefaultApnUri(subId), null, null);
				debug("will return true");
				return true;
			}
		}
        return false;
    }       

    private Uri getDefaultApnUri(int subId) {
		Uri defaultUri = Uri.withAppendedPath(DEFAULTAPN_URI, "/subId/" + subId);
		debug("default apn uri : " + defaultUri);
        return defaultUri;
    }
	/* 2.5 restore to defualt end */

	/* 2.7 add apn */
    /**
     * Check the key fields' validity and save if valid.
     * @param force save even if the fields are not valid, if the app is
     *        being suspended
     * @return true if there's no error
     */
    public boolean addApn(APN newApn, boolean force) {
       	debug("validateAndSave... force = " + force);

        String name = checkNotSet(newApn.getName());
        String apn = checkNotSet(newApn.getApn());
        String mcc = checkNotSet(newApn.getMcc());
        String mnc = checkNotSet(newApn.getMnc());
		String apnType = newApn.getApnType();
		debug("name = " + name + ", apn = " + apn);
		debug("mcc = " + mcc + ", mnc = " + mnc);
		debug("apnType = " + apnType);

		Uri uri = mUri;
		uri = mContext.getContentResolver().insert(uri, new ContentValues());
		debug("uri = " + uri);

        if ( !force  
				&& ( (name.length() < 1) 
					|| (mcc.length() != 3) 
					|| ((mnc.length() & 0xFFFE) != 2)
					|| ( (apnType == null || !apnType.contains("ia")) 
						 && apn.length() < 1))){
			debug("force = false, and teturn");
			return false;
        }
        // If it's a new APN and a name or apn haven't been entered, then erase the entry
        if (force && name.length() < 1 && apn.length() < 1 && uri != null) {
            mContext.getContentResolver().delete(uri, null, null);
            uri = null;
			debug("force = true, and teturn");
            return false;
        }

		ContentValues values = new ContentValues();

		values.put(Telephony.Carriers.NAME, name);
		values.put(Telephony.Carriers.APN, apn);
		values.put(Telephony.Carriers.PROXY, checkNotSet(newApn.getProxy()));
		values.put(Telephony.Carriers.PORT, checkNotSet(newApn.getPort()));
		values.put(Telephony.Carriers.USER, checkNotSet(newApn.getUser()));
		values.put(Telephony.Carriers.PASSWORD, checkNotSet(newApn.getPassword()));
		values.put(Telephony.Carriers.SERVER, checkNotSet(newApn.getServer()));
		values.put(Telephony.Carriers.MMSC, checkNotSet(newApn.getMmsc()));
		values.put(Telephony.Carriers.MMSPROXY, checkNotSet(newApn.getMmsproxy()));
		values.put(Telephony.Carriers.MMSPORT, checkNotSet(newApn.getMmsport()));

		values.put(Telephony.Carriers.AUTH_TYPE, newApn.getAuthTypeVal());
		values.put(Telephony.Carriers.TYPE, apnType);
		values.put(Telephony.Carriers.PROTOCOL, checkNotSet(newApn.getApnProtocol()));
		values.put(Telephony.Carriers.ROAMING_PROTOCOL, checkNotSet(newApn.getRoamingProtocol() ));
		//values.put(Telephony.Carriers.CARRIER_ENABLED, getCarrierEnabled());

		values.put(Telephony.Carriers.MCC, mcc);
		values.put(Telephony.Carriers.MNC, mnc);
		values.put(Telephony.Carriers.NUMERIC, mcc + mnc);
		debug("values = " + values);

		String numeric = SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC);
		debug("numeric = " + numeric);		

		String curMnc = null;
		String curMcc = null;
		// MCC is first 3 chars and then in 2 - 3 chars of MNC
		if (numeric != null && numeric.length() > 4) {
			// Country code
			curMcc = numeric.substring(0, 3);
			// Network code
			curMnc = numeric.substring(3);
			debug("curMcc = " + curMcc + ", curMnc = " + curMnc);
		}
		if (curMnc != null && curMcc != null) {
			if (curMnc.equals(mnc) && curMcc.equals(mcc)) {
				values.put(Telephony.Carriers.CURRENT, 1);
			}
		}

		String bearerVal = newApn.getBearerVal();
		if (bearerVal != null) {
			values.put(Telephony.Carriers.BEARER, Integer.parseInt(bearerVal));
		}

        values.put(MtkTelephony.Carriers.SOURCE_TYPE, 1);
		debug("values = " + values);

		int count = 0;
		if (uri != null) {
			count = mContext.getContentResolver()
					.update(uri, values, null, null);
			debug("111 count = " + count);
		}
		debug("222 count = " + count);

		return count > 0 ? true : false;
    }

	/* 2.8 get mcc and mnc */
	public String getMccMnc(int slotId){
		int subId = MtkSubscriptionManager.getSubIdUsingPhoneId(slotId);
		debug("enter getMccMnc() slotId = " + slotId + ", subId = " + subId);

		String mccmnc = mTelephonyManager.getSimOperator(subId);
		debug("mccmnc = " + mccmnc);

		/*String mccmnc = null;
		Cursor cursor = null;
		try{
			cursor = mResolver.query(getPreferApnUri(subId), PROJECTION,
				        null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
			debug("cursor = " + cursor + " : " + cursor.getCount());

		    if (cursor.getCount() > 0) {//if (cur != null && cur.moveToFirst())
		        cursor.moveToFirst();
				mccmnc = cursor.getString(11) + cursor.getString(12);
		    }
		    debug("mccmnc = " + mccmnc);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			if(cursor!=null)
			cursor.close();
		}*/
        return mccmnc;
	}
	private void debug(String str) {
		if (DEBUG) {
			Log.d(TAG, str);
		}
	}
}

参考:
    https://blog.csdn.net/gf771115/article/details/8212671
    https://blog.csdn.net/lll1204019292/article/details/52260817
    https://www.cnblogs.com/sishuiliuyun/p/3754516.html
    https://yq.aliyun.com/ziliao/116416
    https://blog.csdn.net/treasure3334/article/details/7816361
    https://blog.csdn.net/zidan_2011/article/details/7704865

猜你喜欢

转载自blog.csdn.net/lyl0530/article/details/81006111
APN
今日推荐