Android设置APN
背景
- 需:因公司设备需要更换物联网卡,但最新的物联网卡APN信息在设备数据库中不存在,所以不能自动识别联网,需要手动配置APN信息并选中。
- 查:通过adb查看设备apns-conf.xml中已有APN信息。
adb root
adb remount
adb pull /system/etc/apns-conf.xml
思路
-
系统设置中有APN设置的界面,让安装团队人为手动去点击添加APN信息,解决
撒花哈哈哈,跑去找运维大哥然后被大哥打了一顿。
-
无奈只能通过技术手段开发写入apn信息并选中,毕竟打不过。
技术实现
-
通过content://telephony/carriers 获取APN列表,并写入apn信息。
-
通过content://telephony/carriers/preferapn 设置当前选中apn。
-
判断当前apn是否选中我想要的信息(如cmiot),如为-1则未选中,那我们就要去设置设置。
//当前APN选中项 public static int getSelectAPN(Context context, String apn){ ContentResolver resolver = context.getContentResolver(); String apn_condition = String.format("apn like '%%%s%%'", apn); Cursor c = resolver.query(APN_URI, null, apn_condition, null, null); // 该项APN存在 if (c != null && c.moveToNext()) { int id = c.getShort(c.getColumnIndex("_id")); String name = c.getString(c.getColumnIndex("name")); String apnn = c.getString(c.getColumnIndex("apn")); Log.e("APN has exist", id + name + apnn); return id; } return -1; }
-
没选中可能是因为都没有我要的apn信息,那我们需要添加一下。
//设置添加APN public static int settingAddAPN(Context context, String apnName,String apn) { int id = -1; String NUMERIC = getSIMInfo(context); if (TextUtils.isEmpty(NUMERIC)||NUMERIC.length()<3) { return -1; } ContentResolver resolver = context.getContentResolver(); ContentValues values = new ContentValues(); values.put("name", apnName);//apn中文描述 values.put("apn", apn);//apn名称 values.put("type", "default");//apn类型 values.put("numeric", NUMERIC); values.put("mcc", NUMERIC.substring(0, 3)); values.put("mnc", NUMERIC.substring(3, NUMERIC.length())); values.put("proxy", "");//代理 values.put("port", "");//端口 values.put("mmsproxy", "");//彩信代理 values.put("mmsport", ""); //彩信端口 values.put("user", "");//用户名 values.put("server", ""); //服务器 values.put("password", "");//密码 values.put("mmsc", "");//MMSC Cursor c = null; Uri newRow = resolver.insert(APN_URI, values); if (newRow != null) { c = resolver.query(newRow, null, null, null, null); int idIndex = c.getColumnIndex("_id"); c.moveToFirst(); id = c.getShort(idIndex); } if (c != null) c.close(); return id; }
-
添加后需要在给apn设置选中此信息。
//设置APN接入点 public static int selectAPN(Context context, int id) { ContentResolver resolver = context.getContentResolver(); ContentValues values = new ContentValues(); values.put("apn_id", id); int update=resolver.update(CURRENT_APN_URI, values,null, null); return update; }
完结撒花,可以让运维大哥下次下手轻点了。
- 具体调用流程(例:apn为cmiot,apn_name为huazi)
```
int apn_id = APNUtli.getSelectAPN(this, apn);
if (apn_id == -1) {
apn_id = APNUtli.settingAddAPN(this, apn_name, apn);
if (apn_id == -1) {
Log.d(TAG, "设置APN失败");
}
}
if (apn_id != -1) {
if (APNUtli.selectAPN(this, apn_id) > 0) {
Log.d(TAG, "设置APN成功");
}
}
```