android網絡接點

項目中寫的網絡模塊,感覺有點亂:兩套代碼 --模擬器、真機,維護起來十分麻煩。

解決辦法:代碼自動去檢查到那種網絡環境,然後調用不同的聯網方式。

查看了模擬器上默認的接入點:移動網絡  -- APN = "internet"

1、通過獲取apn的名稱,來判斷網絡

// 獲取Mobile網絡下的cmwap、cmnet
private int getCurrentApnInUse() {
int type = NONET;


Cursor cursor = context.getContentResolver().query(PREFERRED_APN_URI,
new String[] { "_id", "apn", "type" }, null, null, null);
cursor.moveToFirst();
int counts = cursor.getCount();
if(counts != 0){//適配平板外掛3G模塊情況
    if (!cursor.isAfterLast()) {
            String apn = cursor.getString(1);
            //#777、ctnet 都是中國電信定製機接入點名稱,中國電信的接入點:Net、Wap都採用Net即非代理方式聯網即可
            //internet 是模擬器上模擬接入點名稱
            if (apn.equalsIgnoreCase("cmnet") || apn.equalsIgnoreCase("3gnet") || apn.equalsIgnoreCase("uninet")
                    || apn.equalsIgnoreCase("#777") || apn.equalsIgnoreCase("ctnet") ||apn.equalsIgnoreCase("internet")) {
                type = WIFIAndCMNET;
            } else if (apn.equalsIgnoreCase("cmwap") || apn.equalsIgnoreCase("3gwap") || apn.equalsIgnoreCase("uniwap")) {
                type = CMWAP;
            }
        }else{
            //適配中國電信定製機,如海信EG968,上面方式獲取的cursor爲空,所以換種方式
            Cursor c = context.getContentResolver().query(PREFERRED_APN_URI,null, null, null, null);
            c.moveToFirst();
            String user=c.getString(c.getColumnIndex("user"));
            if(user.equalsIgnoreCase("ctnet")){
                type = WIFIAndCMNET;
            }
            c.close();
        }
}else{
    type = WIFIAndCMNET;//平板外掛3G,採用非代理方式上網
}
cursor.close();


return type;
}


2、直接獲取代理參數:proxy 來判斷是否爲代理

/**
 * MOBILE方式下獲取當前的網絡連接方式,代理或非代理
 * 
 */
public static String getCurrentApnInUse(Context context)
{
Cursor cursor = context.getContentResolver().query(PREFERRED_APN_URI, new String[] { "_id", "apn", "type", "proxy" }, null, null,
null);
cursor.moveToFirst();
if (cursor.isAfterLast())
{
String apn = cursor.getString(3);

if (apn == null)

{

apn = "";

}

}

return apn;
}


/**
 * 獲取手機卡類型,移動、聯通、電信
 * 
 */
private static int getMobileType(Context context)
{
int type = 0;
TelephonyManager iPhoneManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String iNumeric = iPhoneManager.getSimOperator();
if (iNumeric.length() > 0)
{
if (iNumeric.equals("46000") || iNumeric.equals("46002"))
{
// 中國移動
}
else if (iNumeric.equals("46001"))
{
// 中國聯通
}
else if (iNumeric.equals("46003"))
{
// 中國電信
}
}

}

發佈了4 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章