转自:http://blog.youkuaiyun.com/skiffloveblue/article/details/7920655
由于Android对于APN的网络API没有公开,不过我们可以阅读源代码,然后进行数据库操作,系统会自动监听数据库的变化,从而实现开启或者关闭APN。
大家可以研究一下frameworks/base/core/java/android/provider/Telephony.java这个类,
比较重要的就是 URI 和数据库字段: content://telephony/carriers
字段可以在Telephony.java中找到。
其实原理很简单 :
1 、 当开启APN的时候,设置一个正确的移动或者联通的APN
2、 关闭的时候设置一个错误APN就会自动关闭网络
请看代码:Activity:
- package cc.mdev.apn;
- import java.util.ArrayList;
- import java.util.List;
- import android.app.Activity;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- /**
- * 這裡是Activity
- * @author SinFrancis wong
- * @site http://mdev.cc
- * @wiki http://mdev.cc/wiki
- * @since 2010-01-08
- */
- public class Mainextends Activity {
- /** Called when the activity is first created. */
- Uri uri = Uri.parse("content://telephony/carriers");
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button open= (Button) findViewById(R.id.open);
- Button close= (Button) findViewById(R.id.close);
- open.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- openAPN();
- }
- });
- close.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- closeAPN();
- }
- });
- }
- public void openAPN(){
- List<APN> list = getAPNList();
- for (APN apn : list) {
- ContentValues cv = new ContentValues();
- cv.put("apn", APNMatchTools.matchAPN(apn.apn));
- cv.put("type", APNMatchTools.matchAPN(apn.type));
- getContentResolver().update(uri, cv, "_id=?",new String[]{apn.id});
- }
- }
- public void closeAPN(){
- List<APN> list = getAPNList();
- for (APN apn : list) {
- ContentValues cv = new ContentValues();
- cv.put("apn", APNMatchTools.matchAPN(apn.apn)+"mdev");
- cv.put("type", APNMatchTools.matchAPN(apn.type)+"mdev");
- getContentResolver().update(uri, cv, "_id=?", new String[]{apn.id});
- }
- }
- private List<APN> getAPNList(){
- String tag = "Main.getAPNList()";
- //current不为空表示可以使用的APN
- String projection[] = { "_id,apn,type,current"};
- Cursor cr = this.getContentResolver().query(uri, projection,null, null,null);
- List<APN> list = new ArrayList<APN>();
- while(cr!=null && cr.moveToNext()){
- Log.d(tag, cr.getString(cr.getColumnIndex("_id")) +" " + cr.getString(cr.getColumnIndex("apn")) +