Android APN Enforcement

守給你的承諾、 提交于 2019-11-30 05:30:54
patthoyts

You can programmatically query and set the preferred APN using the uri content://telephony/carriers/preferapn. To set a new preferred APN you have to pass in the database ID of an existing APN entry. The following function can do this if you pass in the display name of the APN (eg: setPreferredApn(context, "Giffgaff");)

public static final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
public static final Uri APN_PREFER_URI = Uri.parse("content://telephony/carriers/preferapn");

public static boolean setPreferredApn(Context context, String name) {
    boolean changed = false;
    String columns[] = new String[] { Carriers._ID, Carriers.NAME };
    String where = "name = ?";
    String wargs[] = new String[] {name};
    String sortOrder = null;
    Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
    if (cur != null) {
        if (cur.moveToFirst()) {
            ContentValues values = new ContentValues(1);
            values.put("apn_id", cur.getLong(0));
            if (context.getContentResolver().update(APN_PREFER_URI, values, null, null) == 1)
                changed = true;
        }
        cur.close();
    }
    return changed;
}

I guess I should add that you need WRITE_APN_SETTINGS permission and need to import android.provider.Telephony and android.provider.Telephony.Carriers

UPDATE FOR 4.0+

This facility became disabled with the release of Android 4.0 (ICS). Enabling the WRITE_APN_SETTINGS permission has no effect on allowing you to set the APN any more. See this question for some relevant links. On the API page it now states explicitly this permission is not for external use and this is enforced internally.

I dont think there is a way, even if there is one, the carrier could wipe it out with a software update. Also, for some carriers like AT&T in US, using a specific APN provides specific functionality, like getting the Subscriber number of that user (its a unique ID, not the phone number). So it may not be a good idea to force this change, as it will impact numerous other apps installed on handset.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!