|
public class ApnHandler { |
|
|
|
private final static Uri APN_LIST_URI = Uri.parse("content://telephony/carriers"); |
|
private final static Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn"); |
|
|
|
private Context context; |
|
|
|
public ApnHandler(Context context) { |
|
this.context = context; |
|
} |
|
|
|
public boolean configureApn(ApnInfo apnInfo) { |
|
boolean ret; |
|
|
|
ContentValues contentValues; |
|
|
|
try { |
|
contentValues = NetworkUtils.getContentValuesForApnInfo(context, apnInfo); |
|
} catch (SimCardNotFoundException e) { |
|
e.printStackTrace(); |
|
return false; |
|
} |
|
|
|
ret = findApn(apnInfo.getApn()); |
|
if (!ret) { |
|
int apnId = addNewApn(context, contentValues); |
|
if (apnId != -1) { |
|
ret = setApn(apnId) == 1; |
|
} |
|
} |
|
|
|
return ret; |
|
} |
|
|
|
private int addNewApn(Context context, ContentValues contentValues) { |
|
|
|
int id = -1; |
|
|
|
ContentResolver contentResolver = context.getContentResolver(); |
|
|
|
Uri newUri = contentResolver.insert(APN_LIST_URI, contentValues); |
|
Cursor c = null; |
|
if (newUri != null) { |
|
c = contentResolver.query(newUri, null, null, null, null); |
|
int idIndex = c.getColumnIndex("_id"); |
|
c.moveToFirst(); |
|
id = c.getShort(idIndex); |
|
} |
|
if (c != null) { |
|
c.close(); |
|
} |
|
return id; |
|
} |
|
|
|
private int setApn(long id) { |
|
ContentResolver contentResolver = context.getContentResolver(); |
|
ContentValues contentValues = new ContentValues(); |
|
contentValues.put("apn_id", id); |
|
return contentResolver.update(PREFERRED_APN_URI, contentValues, null, null); |
|
} |
|
|
|
private boolean findApn(String name) { |
|
boolean found = false; |
|
String columns[] = new String[] { "_id", "apn"}; |
|
String where = "apn = ?"; |
|
String wargs[] = new String[] {name}; |
|
String sortOrder = null; |
|
Cursor cur = context.getContentResolver().query(APN_LIST_URI, columns, where, wargs, sortOrder); |
|
if (cur != null) { |
|
if (cur.moveToFirst()) { |
|
Log.d("ApnHandler", "APN " + cur.getString(1)); |
|
found = true; |
|
setApn(cur.getLong(0)); |
|
} |
|
cur.close(); |
|
} |
|
return found; |
|
} |
|
} |