Android 自定义网络移动网络接入点

来源:互联网 发布:上海私人调查公司 知乎 编辑:程序博客网 时间:2024/04/29 22:57

1.点击“Network”将显示本机的无线及网络信息。

2.点击"WAP"将自动设接入点为CMWAP。

3.点击“GPRS”将自动设接入点为GPRS。
代码出处:http://blog.csdn.net/sodino/article/details/5916641

标签:Android SDKcmwap GPRS

代码片段(6)

[代码] [Java]代码

view source
print?
001package lab.sodino.network;
002import java.net.InetAddress;
003import java.net.NetworkInterface;
004import java.net.SocketException;
005import java.net.UnknownHostException;
006import java.util.Enumeration;
007import android.app.Activity;
008import android.content.ContentResolver;
009import android.content.ContentValues;
010import android.content.Context;
011import android.database.Cursor;
012import android.net.ConnectivityManager;
013import android.net.NetworkInfo;
014import android.net.Uri;
015import android.net.wifi.WifiInfo;
016import android.net.wifi.WifiManager;
017import android.os.Bundle;
018import android.util.Log;
019import android.view.Menu;
020import android.view.MenuItem;
021import android.view.View;
022import android.view.View.OnClickListener;
023import android.widget.Button;
024import android.widget.TextView;
025/**
026* 1.点击"Network"将输出本机所处的网络环境。 2.点击"WAP"将设定 移动网络接入点为CMWAP。 3.点击"GPRS"将设定
027* 移动网络接入点为CMNET。 注:自定义移动网络接入点的前提是“设置”→“无线和网络”→“移动网络”处已打勾。
028*/
029public class NetworkAct extendsActivity {
030    /** 全部的APN */
031    privatestatic final Uri ALL_APN_URI = Uri
032            .parse("content://telephony/carriers");
033    /** 当前default的APN记录。 */
034    privatestatic final Uri PREFERRED_APN_URI = Uri
035            .parse("content://telephony/carriers/preferapn");
036    privateTextView textView;
037    privateButton btnShowNetInfo;
038    privateButton btnSetCMWAP;
039    privateButton btnSetGPRS;
040    privateBtnClickListener btnListener;
041    privateContentValues cvWAP;
042    privateContentValues cvGPRS;
043    publicvoid onCreate(Bundle savedInstanceState) {
044        super.onCreate(savedInstanceState);
045        setContentView(R.layout.main);
046        textView = (TextView) findViewById(R.id.infoPanel);
047        textView.setBackgroundColor(0xffffffff);
048        textView.setTextColor(0xff0000ff);
049        textView.setTextSize(15.0f);
050        textView.setScrollBarStyle(TextView.SCROLLBARS_OUTSIDE_OVERLAY);
051        btnListener =new BtnClickListener();
052        btnShowNetInfo = (Button) findViewById(R.id.showInfo);
053        btnShowNetInfo.setOnClickListener(btnListener);
054        btnSetCMWAP = (Button) findViewById(R.id.setCMWAP);
055        btnSetCMWAP.setOnClickListener(btnListener);
056        btnSetGPRS = (Button) findViewById(R.id.setGPRS);
057        btnSetGPRS.setOnClickListener(btnListener);
058        initAPNValues();
059    }
060    privatevoid initAPNValues() {
061        cvWAP =new ContentValues();
062        cvWAP.put("name","移动梦网");
063        cvWAP.put("apn","cmwap");
064        // 需要设置为默认接入点则为default
065        cvWAP.put("type","default");
066        cvWAP.put("proxy","10.0.0.172");
067        cvWAP.put("port","80");
068        cvWAP.put("mmsproxy","10.0.0.172");
069        cvWAP.put("mmsport","80");
070        cvWAP.put("mmsprotocol","2.0");
071        cvWAP.put("mmsc","http://mmsc.monternet.com");
072        cvWAP.put("mcc","460");
073        cvWAP.put("mnc","02");
074        cvWAP.put("numeric","46002");
075        cvGPRS =new ContentValues();
076        cvGPRS.put("name","GPRS");
077        cvGPRS.put("apn","cmnet");
078        // 需要设置为默认接入点则为default
079        cvGPRS.put("type","default");
080        // cvGPRS.put("proxy", "10.0.0.172");
081        // cvGPRS.put("port", "80");
082        // cvGPRS.put("mmsproxy", "10.0.0.172");
083        // cvGPRS.put("mmsport", "80");
084        cvGPRS.put("mmsprotocol","2.0");
085        // cvGPRS.put("mmsc", "http://mmsc.monternet.com");
086        cvGPRS.put("mcc","460");
087        cvGPRS.put("mnc","02");
088        cvGPRS.put("numeric","46002");
089    }
090    privatevoid showNetworkInfo() {
091        getLocalAddress();
092        getWifiAddress();
093        getNetworkInfo();
094        textView.append("/nList Default Access Point Name:/n");
095        listAllAPNs(PREFERRED_APN_URI);
096        textView.append("/nList all Access Point Name:/n");
097        listAllAPNs(ALL_APN_URI);
098    }
099    privatevoid getLocalAddress() {
100        InetAddress iAdd =null;
101        try{
102            iAdd = InetAddress.getLocalHost();
103            String line ="";
104            // line = "HostName=" + iAdd.getHostName() + "/n";
105            // textView.append(line);
106            // line = "CanonicalHostName=" + iAdd.getCanonicalHostName() + "/n";
107            // textView.append(line);
108            // line = "HostAddress=" + iAdd.getHostAddress() + "/n";
109            // textView.append(line);
110            // textView.append("/n");
111            String hostName = iAdd.getHostName();
112            if(hostName != null) {
113                InetAddress[] adds =null;
114                adds = InetAddress.getAllByName(hostName);
115                if(adds != null) {
116                    for(int i = 0; i < adds.length; i++) {
117                        iAdd = adds[i];
118                        line ="HostName=" + iAdd.getHostName() +"/n";
119                        textView.append(line);
120                        line ="CanonicalHostName="
121                                + iAdd.getCanonicalHostName() +"/n";
122                        textView.append(line);
123                        line ="HostAddress=" + iAdd.getHostAddress() +"/n";
124                        textView.append(line);
125                        textView.append("/n");
126                    }
127                }
128            }
129        }catch (UnknownHostException e1) {
130            e1.printStackTrace();
131        }
132        try{
133            for(Enumeration<NetworkInterface> en = NetworkInterface
134                    .getNetworkInterfaces(); en.hasMoreElements();) {
135                NetworkInterface intf = en.nextElement();
136                for(Enumeration<InetAddress> enumIpAddr = intf
137                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
138                    InetAddress inetAddress = enumIpAddr.nextElement();
139                    // if (!inetAddress.isLoopbackAddress()) {
140                    textView.append("HostAddress="
141                            + inetAddress.getHostAddress() +"/n");
142                    // }
143                }
144            }
145        }catch (SocketException ex) {
146            Log.e("WifiPreference IpAddress", ex.toString());
147        }
148    }
149    privatevoid getWifiAddress() {
150        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
151        WifiInfo info = wifi.getConnectionInfo();
152        textView.append("HiddenSSID="+ info.getHiddenSSID() + "/n");
153        textView.append("IpAddress="+ formatIP4(info.getIpAddress()) + "/n");
154        textView.append("LinkSpeed="+ info.getLinkSpeed() + "/n");
155        textView.append("NetworkId="+ info.getNetworkId() + "/n");
156        textView.append("Rssi="+ info.getRssi() + "/n");
157        textView.append("SSID="+ info.getSSID() + "/n");
158        textView.append("MacAddress="+ info.getMacAddress() + "/n");
159    }
160    privatevoid getNetworkInfo() {
161        // 此处输出可用网络类型
162        ConnectivityManager mag = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
163        textView.append("/nActive:/n");
164        NetworkInfo info = mag.getActiveNetworkInfo();
165        if(info != null) {
166            textView.append("ExtraInfo="+ info.getExtraInfo() + "/n");
167            textView.append("SubtypeName="+ info.getSubtypeName() + "/n");
168            textView.append("TypeName="+ info.getTypeName() + "/n");
169            textView.append("Type="+ info.getType() + "/n");
170        }
171        textView.append("/nWifi:/n");
172        NetworkInfo wifiInfo = mag
173                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
174        textView.append("ExtraInfo="+ wifiInfo.getExtraInfo() + "/n");
175        textView.append("SubtypeName="+ wifiInfo.getSubtypeName() + "/n");
176        textView.append("TypeName="+ wifiInfo.getTypeName() + "/n");
177        textView.append("Type="+ wifiInfo.getType() + "/n");
178        NetworkInfo mobInfo = mag
179                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
180        textView.append("/nMobile:/n");
181        textView.append("ExtraInfo="+ mobInfo.getExtraInfo() + "/n");
182        textView.append("SubtypeName="+ mobInfo.getSubtypeName() + "/n");
183        textView.append("TypeName="+ mobInfo.getTypeName() + "/n");
184        textView.append("Type="+ mobInfo.getType() + "/n");
185    }
186    privatevoid listAllAPNs(Uri apnUri) {
187        ContentResolver contentResolver = getContentResolver();
188        Cursor cursor = contentResolver.query(apnUri,null, null,null, null);
189        if(cursor != null) {
190            String temp ="Count=" + cursor.getCount() +" ColumnCount="
191                    + cursor.getColumnCount() +"/n";
192            textView.append(temp);
193            String key ="";
194            while(cursor.moveToNext()) {
195                key ="position";
196                intposition = cursor.getPosition();
197                textView.append("/n"+ key + "=" + String.valueOf(position)
198                        +"/n");
199                key ="_id";
200                intid = cursor.getShort(cursor.getColumnIndex(key));
201                textView.append(key +"=" + String.valueOf(id) +"/n");
202                appendDBColumn(cursor,"name");
203                appendDBColumn(cursor,"apn");
204                appendDBColumn(cursor,"type");
205                appendDBColumn(cursor,"proxy");
206                appendDBColumn(cursor,"port");
207                appendDBColumn(cursor,"mmsproxy");
208                appendDBColumn(cursor,"mmsport");
209                appendDBColumn(cursor,"mmsprotocol");
210                appendDBColumn(cursor,"mmsc");
211                appendDBColumn(cursor,"current");
212                appendDBColumn(cursor,"mcc");
213                appendDBColumn(cursor,"mnc");
214                appendDBColumn(cursor,"numeric");
215            }
216        }
217    }
218    privatevoid appendDBColumn(Cursor cursor, String key) {
219        try{
220            String value = cursor.getString(cursor.getColumnIndex(key));
221            textView.append(key +"=" + value + "/n");
222        }catch (Exception e) {
223            System.out.println("[sodino] "+ e);
224        }
225    }
226    privatevoid setNetworkFeature() {
227        // 经测试,start和stop都无效。
228        ConnectivityManager connectivityMag = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
229        intstop = connectivityMag.stopUsingNetworkFeature(
230                ConnectivityManager.TYPE_WIFI,"*");
231        textView.append("stop="+ String.valueOf(stop) + "/n");
232        intstart = connectivityMag.startUsingNetworkFeature(
233                ConnectivityManager.TYPE_MOBILE,
234                ConnectivityManager.EXTRA_NETWORK_INFO);
235        textView.append("start="+ String.valueOf(start) + "/n");
236    }
237    privatevoid setDefaultAPN(ContentValues value) {
238        int_id = findAPNId(value);
239        if(_id == -1) {
240            _id = insertAPN(value);
241        }
242        textView.append(value.get("name") +" _id=" + _id + "/n");
243        ContentValues values =new ContentValues();
244        values.put("apn_id", _id);
245        ContentResolver resolver = getContentResolver();
246        intupdateRow = resolver.update(PREFERRED_APN_URI, values, null, null);
247        textView.append("updateRow="+ updateRow + "/n");
248        textView.append("Set "+ value.get("name")
249                +" as default netwrok successed!!/n");
250    }
251    privateint findAPNId(ContentValues cv) {
252        intid = -1;
253        ContentResolver contentResolver = getContentResolver();
254        Cursor cursor = contentResolver.query(ALL_APN_URI,null, null,null,
255                null);
256        if(cursor != null) {
257            while(cursor.moveToNext()) {
258                if(cursor.getString(cursor.getColumnIndex("name")).equals(
259                        cv.get("name"))
260                        && cursor.getString(cursor.getColumnIndex("apn"))
261                                .equals(cv.get("apn"))
262                        && cursor.getString(cursor.getColumnIndex("numeric"))
263                                .equals(cv.get("numeric"))) {
264                    id = cursor.getShort(cursor.getColumnIndex("_id"));
265                    break;
266                }
267            }
268        }
269        returnid;
270    }
271    privateint insertAPN(ContentValues value) {
272        intapn_Id = -1;
273        ContentResolver resolver = getContentResolver();
274        Uri newRow = resolver.insert(ALL_APN_URI, value);
275        if(newRow != null) {
276            Cursor cursor = resolver.query(newRow,null,null,null,null);
277            intidIdx = cursor.getColumnIndex("_id");
278            cursor.moveToFirst();
279            apn_Id = cursor.getShort(idIdx);
280            System.out.println("[sodino] Insert New id:"+ apn_Id);
281        }
282        returnapn_Id;
283    }
284    publicboolean onCreateOptionsMenu(Menu menu) {
285        menu.add("finish");
286        returntrue;
287    }
288    publicboolean onOptionsItemSelected(MenuItem item) {
289        if(item.getTitle().equals("finish")) {
290            finish();
291        }
292        returnfalse;
293    }
294    /** 将10进制整数形式转换成127.0.0.1形式的IP地址 */
295    privatestatic String formatIP4(longlongIP) {
296        StringBuffer sb =new StringBuffer("");
297        sb.append(String.valueOf(longIP >>>24));
298        sb.append(".");
299        sb.append(String.valueOf((longIP &0x00FFFFFF) >>> 16));
300        sb.append(".");
301        sb.append(String.valueOf((longIP &0x0000FFFF) >>> 8));
302        sb.append(".");
303        sb.append(String.valueOf(longIP &0x000000FF));
304        returnsb.toString();
305    }
306    privateclass BtnClickListenerimplements OnClickListener {
307        publicvoid onClick(View v) {
308            textView.setText("");
309            if(v == btnShowNetInfo) {
310                showNetworkInfo();
311            }else if(v == btnSetCMWAP) {
312                setDefaultAPN(cvWAP);
313                btnSetCMWAP.setEnabled(false);
314                btnSetGPRS.setEnabled(true);
315            }else if(v == btnSetGPRS) {
316                setDefaultAPN(cvGPRS);
317                btnSetGPRS.setEnabled(false);
318                btnSetCMWAP.setEnabled(true);
319            }
320        }
321    }
322}

[代码] [XML]代码

view source
print?
01<?xmlversion="1.0"encoding="utf-8"?>
02<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
03    android:orientation="vertical"
04    android:layout_width="fill_parent"
05    android:layout_height="fill_parent"
06    >
07    <LinearLayout
08        android:layout_width="fill_parent"
09        android:layout_height="wrap_content"
10        android:orientation="horizontal">
11        <Button
12            android:id="@+id/showInfo"
13            android:layout_width="wrap_content"
14            android:layout_height="wrap_content"
15            android:layout_weight="2"
16            android:text="Network"
17        ></Button>
18        <Button
19            android:id="@+id/setCMWAP"
20            android:layout_width="wrap_content"
21            android:layout_height="wrap_content"
22            android:layout_weight="1"
23            android:text="WAP"
24        ></Button>
25        <Button
26            android:id="@+id/setGPRS"
27            android:layout_width="wrap_content"
28            android:layout_height="wrap_content"
29            android:layout_weight="1"
30            android:text="GPRS"
31        ></Button>
32    </LinearLayout>
33    <ScrollView
34        android:layout_width="fill_parent"
35        android:layout_height="wrap_content">
36        <TextView
37            android:id="@+id/infoPanel"
38            android:layout_width="fill_parent"
39            android:layout_height="wrap_content"
40        />
41    </ScrollView>
42</LinearLayout>

[代码] [XML]代码

view source
print?
01<?xmlversion="1.0"encoding="utf-8"?>
02<manifestxmlns:android="http://schemas.android.com/apk/res/android"
03    package="lab.sodino.network"android:versionCode="1"
04    android:versionName="1.0">
05    <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
06        <activityandroid:label="@string/app_name"android:name=".NetworkAct">
07            <intent-filter>
08                <actionandroid:name="android.intent.action.MAIN"/>
09                <categoryandroid:name="android.intent.category.LAUNCHER"/>
10            </intent-filter>
11        </activity>
12    </application>
13    <uses-sdkandroid:minSdkVersion="4"/>
14    <!-- 查看网络信息时需要以下权限 -->
15    <uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
16    <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
17    <!-- 设置APN时需要上面的ACCESS_NETWORK_STATE及以下权限 -->
18    <uses-permissionandroid:name="android.permission.WRITE_APN_SETTINGS"></uses-permission>
19    <uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>
20    <!-- 设置网络类型时将要使用 -->
21    <uses-permissionandroid:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
22</manifest>

[图片] 7303_1286788707A168.jpg

[图片] 7303_1286788707dRbs.jpg

[图片] 7303_129784630836V1.jpg

原创粉丝点击