Android 系统APN写入与读取

在Android 4.0及以上版本,设置APN需要`WRITE_APN_SETTINGS`权限。本文介绍了如何添加该权限,并提供了一个查询当前APN的方法,通过ContentResolver查询`CURRENT_APN_URI`来获取APN信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android4.0之后,设置APN需要系统级别的APP才可以。因为系统是自己做的,所以这里我附上一个我所使用的方法,给有需要的人。

1.添加权限:<uses-permission android:name="android.permission.WRITE_APN_SETTINGS"/>
2.变量:public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
    public static final Uri CURRENT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

3. /**新增一个cmnet接入点
        *@name相当于key值,可以自己定
        *@apn就是你真正所要添加的
        */
   
public int addAPN(String name,String apn) {
        int id = -1;
        ContentResolver resolver = this.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("apn", apn);
        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;
    }

4.第三步只是为了得到参数,APN还没做到真正的添加,我们将上一步得到的id,传入以下方法。
    public void SetAPN(int id) {
        ContentResolver resolver = this.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("apn_id", id);
        resolver.update(CURRENT_APN_URI, values, null, null);
    }

5.这样就添加完毕了,接下来提供一个查询APN的方法。

public void checkAPN(){
        // 检查当前连接的APN
        Cursor cr = getContentResolver().query(CURRENT_APN_URI, null, null,
                null, null);
        while (cr != null && cr.moveToNext()) {
            // APN id
            String id = cr.getString(cr.getColumnIndex("_id"));
            // APN name
            String apn = (String)(cr.getString(cr.getColumnIndex("apn")));
            Toast.makeText(getApplicationContext(),
                    "当前 id:" + id + " apn:" + apn, Toast.LENGTH_LONG).show();
        }
    }

不过这个方法只能查询到目前你所使用的APN。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值